我正在尝试创建一个简单的循环,餐厅中有 20 张 table 。客户将能够选择从 1 到 20 的表。因此我为其创建了一个 if else 语句。但如果客户输入的号码超出范围,则会打印错误消息。问题是,如果用户输入错误,我希望它再次询问相同的问题,所以我尝试了 do while 循环。问题是,输出充满错误。谁能帮我解决这个问题吗?
public class MainRestaurant {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Please choose your table from 1-20.");
int table;
int x = 1;
table = sc.nextInt();
do{
if(table >0 && table <21){
System.out.println("Table chosen: " + table);
x=2;
}
else{
System.out.println("Wrong choice");
}
}while(x==1);
}
最佳答案
您应该将 sc.nextInt() 函数移至 do-while 循环中。
do{
table = sc.nextInt();
if(table >0 && table <21){
System.out.println("Table chosen: " + table);
x=2;
}
else{
System.out.println("Wrong choice");
}
} while(x==1);
关于java - 需要在类中实现do、while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20326278/