不显示堆栈中的元素

Not displaying elements from stack

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

这是我的堆栈 class。

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]);
    }

}
}

这里是主要方法class

public class Stackex {
public static void main(String[] args) {
    Stack s = new Stack();
    s.push(2);
    s.push(4);
    s.display();
}

}

当我尝试执行从 isempty() 之后什么都不显示。请在我需要更正此代码的地方帮助我。

您对 push 的调用仅在 isempty returns true.

时才会推送

所以第一次推送成功并将top设置为0。

第二次推送永远不会发生,因为 isempty returns false.

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

修复方法 push & display:

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]);
    }
}

首先要修复一些编译错误。 在方法 display 中没有声明 i,像这样修复它:

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

比改变这个:

private int[] a;;
private int ijk]kkkk 

为此:

private int[] a;

现在您的问题是因为 isempty returns 错误。所以像这样更改推送方法:

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

添加元素时要检查堆栈是否已满。