【问题标题】:Stack Implementation in Java [duplicate]Java中的堆栈实现[重复]
【发布时间】:2016-07-30 20:37:44
【问题描述】:

我正在尝试使用 Java 中的数组来实现堆栈。我的 Stack 类由非静态方法 push、pop、peek 和 isempty 组成。我想测试堆栈实现是在主类中的非静态主方法中实例化堆栈。当我尝试这样做时,我收到一个错误“无法从静态上下文引用非静态方法 push(int)” 我做错了什么?

堆栈.java

public class Stack {

private int top;
private int[] storage;

Stack(int capacity){
    if (capacity <= 0){
        throw new IllegalArgumentException(
                "Stack's capacity must be positive");
    }
    storage = new int[capacity];
    top = -1;
}

void push(int value){
    if (top == storage.length)
        throw new EmptyStackException();
    top++;
    storage[top] = value;
}

int peek(){
    if (top == -1)
        throw new EmptyStackException();
    return storage[top];
}

int pop(){
    if (top == -1)
        throw new EmptyStackException();
    return storage[top];
  }
}

Main.java

public class Main {

public static void main(String[] args) {
    new Stack(5);
    Stack.push(5);
    System.out.println(Stack.pop());

 }
}

【问题讨论】:

  • Stack x = new Stack(5); 然后 x.push();x.pop();
  • 您需要一个变量来保存Stack 对象。 Stack s = new Stack(5); 那么您的方法将在 s 上运行。
  • 你必须在 Stack 类的对象上调用 push
  • 仅供参考: push() 方法中的保护条件是错误的。应该是top == storage.length - 1,异常应该不一样(我的意思是,栈是full,不是empty,对吧?)

标签: java data-structures stack


【解决方案1】:

您创建了一个新实例,但没有将该引用保存在任何地方,因此您在创建后立即丢失了它。相反,您应该将其分配给一个变量,然后对其应用方法:

public static void main(String[] args) {
    Stack stack = new Stack(5);
    stack.push(5); // invoked on an instance "stack"
    System.out.println(stack.pop());
}

【讨论】:

  • 我根据您的评论进行了更改。我收到一个错误线程“main”中的异常 java.lang.NoSuchMethodException: Stack.main([Ljava.lang.String;)
  • 其实我认为那是因为我引用了一个私有变量。谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-11-11
  • 2021-06-24
  • 1970-01-01
  • 1970-01-01
  • 2021-10-22
  • 2013-01-25
  • 2020-10-24
  • 1970-01-01
相关资源
最近更新 更多