Java 不显示堆栈中的元素

Java 不显示堆栈中的元素,java,stack,Java,Stack,所以我为stack编写了这个JAVA程序,问题是我无法使用代码中使用的display()方法显示元素 这是我的堆栈类 public class Stack { //members private int top; private int size; private int[] a; private int i; //constructor public Stack() { this.top = -1; this.size = 5; this.a = new int[si

所以我为stack编写了这个JAVA程序,问题是我无法使用代码中使用的display()方法显示元素

这是我的堆栈类

public class Stack {
//members
private int top;
private int size;
private int[] a;
private int i;

//constructor
public Stack() {
    this.top = -1;
    this.size = 5;
    this.a = new int[size];
}

private boolean isempty() {
    if(top == -1) {
        System.out.println("Stack Underflow");
        return true;
    }
    return false;
}

private boolean isfull() {
    if(top == size-1) {
        System.out.println("Stack Overflow");
        return true;
    }
    return false;
}

public void push(int n) {
if(isempty()) {
    top+=1;
    a[top] = n;
    }
}

public void pop() {
    if(isfull()) {
        System.out.println("popped : "+ a[top]);
        top-=1;         
    }
}

public void display() {
    for(i=0;i<top;i++) {
        System.out.println(a[i]);
    }

}
}

当我尝试执行时,从isempty()中得到的是“堆栈下溢”,之后不会显示任何内容。请帮助我更正此代码。

您对
push
的调用仅在
isempty
返回
true
时才推送

因此,第一次推送成功并将top设置为0

第二次推送从未发生,因为
isempty
返回false


因此,当您转到
display
时,您的
for
循环不会重复,因为
top
为0。

修复方法
推送
&
显示

public void push(int n) {
    if (!isfull()) {
        top += 1;
        a[top] = n;
    }
}

public void display() {
    for (int i = 0; i <= top; i++) {
        System.out.println(a[i]);
    }
}
公共无效推送(int n){
如果(!isfull()){
top+=1;
a[顶部]=n;
}
}
公共空间显示(){

对于(int i=0;i,需要首先修复一些编译错误。 在方法
display
中,未声明
i
,请按如下方式修复它:

public void display() {
    for (int i = 0; i < top; i++) { // add int i = 0
        System.out.println(a[i]);
    }
}
public void push(int n) {
    if (!isfull()) {
        top += 1;
        a[top] = n;
    }
}
为此:

private int[] a;
现在,您的问题是因为
isempty
返回false。因此,更改push方法如下:

public void display() {
    for (int i = 0; i < top; i++) { // add int i = 0
        System.out.println(a[i]);
    }
}
public void push(int n) {
    if (!isfull()) {
        top += 1;
        a[top] = n;
    }
}

添加元素时,您希望检查堆栈是否已满。

欢迎使用堆栈溢出。我将在一分钟内查看代码,但我强烈建议您下一步要做的是在调试器中逐步检查代码,并编辑问题,并根据结果进行编辑。请始终仔细查看该状态,并查看它何时出现成为你意想不到的事情。将来,作为研究的一部分,最好在提问之前这样做。此外,你发布的代码无效也无济于事:你真正的代码肯定没有
private int ijk]kkkk
。需要注意的几件事:1)应该是
isempty()
在第一次调用
push
时将打印“堆栈下溢”。但这是一条奇怪的消息-通常只有在空堆栈上调用
pop
时才会发生。2)
push()
实际上只会推送一个值-因为在此之后,堆栈不是空的。
private int ijk]kkk
很抱歉,ijk]kkk实际上是“i”,当我试图编辑代码时,它会显示“i”,一切正常,但当我在这里发布时,它会显示ijk]kkk