Question

So the code that I have here is:

     public int getCount()
     {
       Scanner s1 = new Scanner(line);
       int count=0; 
       while(s1.hasNextInt());
        {
           int x = s1.nextInt();
           count++;
        }
       return count;
       }

I don't understand why i'm getting the infinite loop when I am using .nextInt(); and following all of my notes.

If any of you could help I would be very thankful.

Thanks so much!

Was it helpful?

Solution

Remove the semi-colon after the while. Because of the semi-colon, the block after the while is an independent block as the while loop terminates at the ; with an empty statement. The while condition always stays true and thus the infinite loop.

while(s1.hasNextInt())

OTHER TIPS

Remove the ; after this line:

while(s1.hasNextInt());

In this case, ; acts as an empty statement, so you have a while-loop containing an empty statement, and after that a block between { and }, which will never be executed because the loop with the empty statement repeats forever.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top