我试图要求用户继续键入数字,直到他们输入-1后,代码会说谢谢你以后再见!我现在被卡住了,因为我的循环是无限循环而我试图在不使用迭代的情况下解决它。这就是我所拥有的。
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int num = Integer.parseInt(reader.nextLine());
while (num < -1 || num > -1) {
System.out.println(num);
if (num == -1) {
System.out.println("Thank you and see you later!");
break;
}
}
答案 0 :(得分:2)
您需要读取循环内的输入。你只做了一次(在进入循环之前)所以num的值永远不会改变。此外,您可以使用while (num != -1)
所以最终,你想要这样的东西:
Scanner reader = new Scanner(System.in);
System.out.println("Type numbers: ");
int num = 0;
while (num != -1) {
num = Integer.parseInt(reader.nextLine());
if (num == -1) {
System.out.println("Thank you and see you later!");
}else{
System.out.println(num);
}
}
答案 1 :(得分:1)
试试这段代码:
Scanner reader = new Scanner(System.in);
int num = 0;
System.out.println("Type numbers: ");
while(true){
//get user input
num = Integer.parseInt(reader.nextLine());
if(num == -1){
System.out.println("Thank you and see you later!");
break;
}
}