java - 不显示堆栈中的元素
问题描述
所以我已经为堆栈编写了这个 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]);
}
}
}
这是主要的方法类
public class Stackex {
public static void main(String[] args) {
Stack s = new Stack();
s.push(2);
s.push(4);
s.display();
}
}
当我尝试执行时,从isempty()得到的是“堆栈下溢” ,之后什么都没有显示。请在我需要更正此代码的地方帮助我。
解决方案
首先要修复一些编译错误。在未声明的方法中,像这样修复它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
返回 false。所以改变 push 方法是这样的:
public void push(int n) {
if (!isfull()) {
top += 1;
a[top] = n;
}
}
添加元素时,您要检查堆栈是否未满。
推荐阅读
- sql - 无法在 oracle 视图中执行具有公共同义词的功能
- amazon - 访问亚马逊 MWS 入站货件
- assembly - 将 yasm 代码(英特尔风格)移植到 gas(AT&T 风格)
- haskell - 尝试将类型 Relation [(a,b)] 定义为 Category 类的实例时出错
- mysql - 如何在 mysql select 中添加这个额外的规定(或条件)?
- reactjs - 未从 React Js 的 .json 文件加载图像
- typescript - 是否可以推断子类上重写方法的参数类型?
- python - 如何在我的 HTML 模板中从此字典中获取值?
- powershell - PowerShell 如何在 Where-Object 中使用 -and
- c++ - 使用 int 和 Points 对向量进行排序