简体   繁体   中英

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

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. 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. However, when you read keyboard input, it will obviously never return false .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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