Java Line 26: error: cannot find symbol: method top() why?


  • 8
    W

    y
    class Stack {

    Queue<Integer> queue1 = new LinkedList<Integer>();
    Queue<Integer> queue2 = new LinkedList<Integer>();
    
    // Push element x onto stack.
    public void push(int x) {
        while (!queue1.isEmpty()) {
            int num = queue1.poll();
            queue2.add(num);
        }
        queue1.add(x);
    }
    
    // Removes the element on top of the stack.
    public void pop() {
        if (!queue1.isEmpty()) {
            queue1.poll();
            return;
        }
        while (queue2.size() != 1) {
            int num = queue2.poll();
            queue1.add(num);
        }
        queue2.poll();
    }
    
    // Get the top element.
    public int top() {
        if (!queue1.isEmpty()) {
            return queue1.peek();
        }
        while (queue2.size() != 1) {
            int num = queue2.poll();
            queue1.add(num);
        }
        int num = queue2.poll();
        queue1.add(num);
        return num;
    }
    
    // Return whether the stack is empty.
    public boolean empty() {
        return queue1.isEmpty() && queue2.isEmpty();
    }
    

    }


  • 5
    R

    My guess is, it is the line 26 from the testing code that makes a wrong invocation, not the line 26 from your code. :(


  • 0
    W

    agree. I have the same problem


  • 1
    P

    I have the same problem and totally have no idea which part is wrong


  • 0

    same problem and don`t know how to deal with that. Do anyone have java solutions that can pass the test case


  • 0

    Thanks for the feedback. I have fixed it by renaming the class name to MyStack. Please rename your class name to MyStack and it should get Accepted.


  • 0
    W

    ok,I try and AC,thx!


  • 0
    W

    this is not the AC code, just use to explain the error.
    please rename your class name to MyStack.


  • 0
    M

    What does this error mean?

    The Cannot find symbol errors generally occur when you try to reference an undeclared variable in your code. A "Cannot find symbol" error means that the compiler cannot do this. Your code appears to be referring to something that the compiler doesn't understand.

    What things can cause this error?

    The general causes for a Cannot find symbol error are things like:

    • Incorrect spelling.
    • Wrong case. Halo is different from halo.
    • Improper use of acceptable identifier values (letters, numbers, underscore, dollar sign), my-class is not the same as myclass.

      No variable declaration or variable is outside of the scope you are referencing it in.

    More about...cannot find symbol Error


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.