【发布时间】:2021-06-08 13:37:24
【问题描述】:
在 do-while 循环中,代码在第一种情况后不接受输入。它在接受输入后被终止并且没有正确执行do-while循环。z = sc.nextLine()有什么问题{在while循环中} 还是 Scanner 类? PS:我也试过 Scanner sc=new Scanner("System.in");但代码仍然不起作用。 除了 parseInt() 之外的任何其他选择?
输出: 堆栈大小? 5 1.推 2.POP 3.显示 1 推号? 19 继续? 继续后,代码被终止
请帮忙。
class stak{
int tos=-1;
int size;
int a[];
stak(int l){
size=l;
tos=-1;
a=new int[l];
}
void push(int x){
if(tos==size-1){
System.out.println("Stack Overflow");
}
else{
a[++tos]=x;
}
}
void pop(){
if(tos<0){
System.out.println("Stack Underflow");
}
else{
System.out.println(a[tos--]);
}
}
void display(){
if(tos>=0){
for(int i=tos;i>=0;--i){
System.out.println(a[i]);
}
}
else
System.out.println("Stack is Empty");
}
}
public class stack{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println("size of stack?");
int n=sc.nextInt();
stak s1=new stak(n);
String z;
do{
System.out.println("1.PUSH");
System.out.println("2.POP");
System.out.println("3.Display");
int ch=sc.nextInt();
switch(ch){
case 1 : System.out.println("number for push?");
int p=sc.nextInt();
s1.push(p);
break;
case 2 : System.out.println("POP!");
s1.pop();
break;
case 3 : System.out.println("Display!");
s1.display();
break;
default: System.out.println(" OOPS! owner says only take input as: 1,2,3");
break;
}
System.out.println("continue?");
z=sc.nextLine();
}while(z.equals("yes")|| z.equals("y"));
sc.close();
}
}
[1]: https://i.stack.imgur.com/BHZQO.png
【问题讨论】:
-
您能否在您的问题中添加一些示例输入,以及您期望的行为是什么
-
以文本形式添加的输出
-
好的,根据该输入,我相信@maloomeister 评论中的链接将解决您的问题
标签: java java.util.scanner do-while