问题描述
我的堆栈程序遇到问题,我不太了解我的错误。我可以帮忙吗?每次我尝试运行它时,它都会出现多个错误,并且在某些方面我非常困惑。我的错误是总共60个错误。 因此整个程序都关闭了。我只是想在此堆栈和队列程序中创建名称。
public class YourStackNB {
private int maxSize;
private long[] stackArray;
private int top;
public YourStackNB(int s) {
maxSize = s;
stackArray = new long[maxSize];
top = -1;
}
public void push(long j) {
stackArray[++top] = j;}
public long pop() {
return stackArray[top--];
}
public boolean isEmpty() {
return (top == -1);
}
public static void main(String[] args) {
YourStackNB theStack = new YourStackNB();
Stack<Name> even = new Stack<>();
theStack.push(dino);
theStack.push(perry);
theStack.push(jada);
theStack.push(holly);
theStack.push(nori);
while (!theStack.isEmpty()) {
long value = theStack.pop();
System.out.print(value);
System.out.print(" ");
}
System.out.println("");
}
}
解决方法
您正在尝试使用数组实现堆栈。但是您没有正确使用它。相反,您尝试通过传递不正确的名称类型来使用java.util.Stack。
您正在尝试实现长数据类型的Stack的另一件事。但是您正在尝试在其中放置一些字符串。这些代码不正确
// Stack<Name> even = new Stack<>();
// theStack.push(dino);
// theStack.push(perry);
// theStack.push(jada);
// theStack.push(holly);
// theStack.push(nori);
我建议您尝试编写一些基本的Java程序,以使您更加了解Java语法,这将有助于您更好地思考。
为了您的学习,我正在修复错误,并且可以以更好的方式实现此代码
public class YourStackNB {
private int maxSize;
private long[] stackArray;
private int top;
public YourStackNB(int s) {
maxSize = s;
stackArray = new long[maxSize];
top = -1;
}
public void push(long j) {
stackArray[++top] = j;}
public long pop() {
return stackArray[top--];
}
public boolean isEmpty() {
return (top == -1);
}
public static void main(String[] args) {
YourStackNB theStack = new YourStackNB(10);
theStack.push(100);
theStack.push(200);
theStack.push(300);
theStack.push(400);
theStack.push(500);
// Stack<Name> even = new Stack<>();
// theStack.push(dino);
// theStack.push(perry);
// theStack.push(jada);
// theStack.push(holly);
// theStack.push(nori);
while (!theStack.isEmpty()) {
long value = theStack.pop();
System.out.print(value);
System.out.print(" ");
}
System.out.println("");
}
}
OUTPUT: 500 400 300 200 100
由于堆栈是后进先出(LIFO),因此打印顺序相反,我们将元素插入其中。