我无法通过这段代码在Java中使用数组实现堆栈,因为我的push()无法在数组中存储值.
UseStack
class UseStack{
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
System.out.println("Enter the size of Stack....");
int n = obj.nextInt();
new Stack(n);
while(true){
System.out.println("1: Push");
System.out.println("2: Show");
int choice = obj.nextInt();;
switch(choice){
case 1:
Push push = new Push(n);
push.push();
break;
case 2:
Push push1 = new Push(n);
push1.show();
break;
default:
System.out.println("Invalid Option");
break;
}
}
}
}Stack.java
class Stack {
public int arr[];
public int top;
public int capacity;
Stack(int size){
this.arr = new int[size];
this.capacity = size;
this.top = -1;
}
}Push.java
class Push extends Stack {
Push(int size) {
super(size);
}
private static Scanner obj;
public void push(){
obj = new Scanner(System.in);
System.out.println("Enter Value to push...");
int value = obj.nextInt();
System.out.println("Value : "+value);
if(top==capacity-1){
System.out.println("StackOverflow");
return;
}
else{
top++;
System.out.println("Top : "+top);
arr[top]=value;
System.out.println("Pushed... "+arr[top]);
}
}
public void show(){
if(top==-1){
System.out.println("StackUnderFlow");
return;
}
else{
System.out.println("Stack Elements : ");
for(int i=top;i>=0;i--){
System.out.println(arr[i]+" ");
}
}
}
}请原谅我的无知,也许还有其他更好的方法来实现堆栈。使用Java的内置堆栈,因为我已经成功地使用它实现了,但是现在我试图通过为每个方法创建不同的类来实现。
**问题:**
Enter the size of Stack....
3
1: Push
2: Show
1
Enter Value to push...
5
Value : 5
Top : 0
Pushed... 5
1: Push
2: Show
1
Enter Value to push...
10
Value : 10
Top : 0
Pushed... 10
1: Push
2: Show
2
StackUnderFlow
1: Push
2: Show如您所见,我的顶级值只增加一次,从-1开始变为0,并且我的值没有存储在数组中,因为每次推送某个元素后,我都希望看到使用show()的元素,它显示的是StackUnderflow。
这个问题似乎很难找出为什么每次都会发生这种事.
发布于 2020-07-04 07:51:15
每次在开关情况下推送和显示时,您都要创建新对象,然后始终在操作前将top初始化为-1。
case 1:
Push push = new Push(n);
push.push();
break;
case 2:
Push push1 = new Push(n);
push1.show();
break;创建一个对象并仅对该对象执行操作
class UseStack{
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
System.out.println("Enter the size of Stack....");
int n = obj.nextInt();
Push push = new Push(n); // Create one object
while(true){
System.out.println("1: Push");
System.out.println("2: Show");
int choice = obj.nextInt();;
switch(choice){
case 1:
push.push(); // Then do operation on that object
break;
case 2:
push.show(); // Then do operation on that object
break;
default:
System.out.println("Invalid Option");
break;
}
}
}
}发布于 2020-07-04 08:10:43
你有设计上的问题。Stack确实是一个类,表示堆栈对象。但是push只是堆栈上的一个操作,因此应该是Stack类以及show和pop的直接方法。我的建议是也实现一个给出当前大小的方法,或者至少测试堆栈是否为空。
在面向对象编程中,您应该创建一个Stack对象并在其上使用方法。这还不是全部。单一关注是一种最佳实践,因此阅读不应该是Stack类的任务:它只应该通过存储对象和返回对象来处理。所以我会把扫描仪和问题移到UseStack课上。
https://stackoverflow.com/questions/62726569
复制相似问题