简体   繁体   English

第二个while循环不断运行,有人可以解释为什么吗?

[英]The second while loop is running endlessly can someone please explain why?

I am trying to get a hang of multiple inputs but I have run into a problem that I cant seem to understand. 我试图将多个输入挂起,但遇到了我似乎无法理解的问题。

I have tried debugging and I have understood where the logical error is occurring but I cant seem to understand why. 我尝试了调试,并且我了解了发生逻辑错误的地方,但是我似乎无法理解为什么。

import java.util.Scanner;
public class Main
{

    public static void main(String args[])
    {
        int i=0;
        Scanner sc=new Scanner(System.in);
        int T=sc.nextInt();
        sc.nextLine();
        while(T!=0)
        {
            System.out.println("First Loop");
           while(sc.hasNext()) {
               System.out.println("Second loop");
               int j=sc.nextInt();
               i=i+j;
           }
           sc.nextLine();
           T=T-1;
        }
        System.out.println("end");
    }
}


2<br>
First Loop<br>
1 2 3 4 5<br>
Second loop<br>
Second loop<br>
Second loop<br>
Second loop<br>
Second loop<br>
1 2 3 4 5<br>
Second loop<br>
Second loop<br>
Second loop<br>
Second loop<br>
Second loop<br>
1 2 3 4 5<br>
Second loop<br>
Second loop<br>
Second loop<br>
Second loop<br>
Second loop<br>

This is whats happening and on and on it goes. 这是正在发生的事情,并且持续不断。 Its an endless loop. 它是一个无尽的循环。

The first line is the number of test cases so the second loop should run twice in this given case however its running endlessly 第一行是测试用例的数量,因此第二个循环在给定的情况下应该运行两次,但是循环不断

I really don't understand what you're trying to do here with 2 while loops, but you can fix the infinite loop problem by simply doing 我真的不明白您在尝试使用2个while循环在这里做什么,但是您可以通过简单地解决无限循环问题

while(sc.hasNextInt()) { //change here
    System.out.println("Second loop");
    int j=sc.nextInt();
    i=i+j;
}

Basically, hasNext() will always return true However, hasNextInt() returns true only if you give it an integer. 基本上, hasNext()将始终返回true但是,只有将整数赋予hasNextInt()返回true。 So you can exit the loop by entering non integer input. 因此,您可以通过输入非整数输入退出循环。

When reading files, hasNext() will ultimately return false when the end of file is reached. 读取文件时,到达文件末尾时, hasNext()最终将返回false However, when you read keyboard input, it will obviously never return false . 但是,当您阅读键盘输入时,显然不会返回false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM