为什么这个 while 循环的条件没有停止循环?

huangapple go评论62阅读模式
英文:

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 &quot;-1&quot; is entered by the user. Instead, a &quot;-1&quot; is inserted into my arraylist before being recognized. I would like to understand why the loop doesn&#39;t stop immediately upon detecting a &quot;-1.&quot;

</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);
}

huangapple
  • 本文由 发表于 2020年9月11日 11:43:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/63840505.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定