英文:
Why isn't this while loop condition stopping the loop?
问题
System.out.println("请输入您的成绩:");
while(scanner.nextInt() != -1){
numbers.add(scanner.nextInt());
}
我有一个while循环,应该在用户输入"-1"后停止。但实际上,在被识别出来之前,"-1"被插入到了我的数组列表中。我想了解为什么循环在检测到"-1"时不立即停止。
<details>
<summary>英文:</summary>
System.out.println("Please enter your grades: ");
while(scanner.nextInt() != -1){
numbers.add(scanner.nextInt());
}
I have a while-loop which is supposed to stop once a "-1" is entered by the user. Instead, a "-1" is inserted into my arraylist before being recognized. I would like to understand why the loop doesn't stop immediately upon detecting a "-1."
</details>
# 答案1
**得分**: 2
你两次调用了 `nextInt`,它每次都会返回一个新的整数。试试这样写:
```java
while (true) {
int val = scanner.nextInt();
if (val == -1) {
break;
}
numbers.add(val);
}
英文:
You're calling nextInt
twice, and it returns a new int each time. Try this:
while(true){
int val = scanner.nextInt();
if (val == -1) {
break;
}
numbers.add(val);
}
答案2
得分: 0
实际上,在每次循环中您都会输入两次输入,因为在 while 循环中调用了 scanner.nextInt()
两次。只需调用一次并在每轮保存输入的值。下面的代码正好实现了您想要的效果:
int nextInt;
while ((nextInt = scanner.nextInt()) != -1) {
numbers.add(nextInt);
}
英文:
Actually, You are typing input twice at each loop because scanner.nextInt()
is called at two places in the while loop. Just call it one time and save typed value at each round. Below code does exactly what you want:
int nextInt;
while((nextInt = scanner.nextInt())!= -1){
numbers.add(nextInt);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论