Flow
Flow

Reputation: 169

While infinite loop

I get an infinite loop in this code

I'm just trying to get the user to reenter the integer just once in the while loop

Where is the problem?

System.out.print ("Enter a number: ");

while (!scan.hasNextInt())
  System.out.print ("reenter as integer: ");
  num = scan.nextInt();

Upvotes: 3

Views: 235

Answers (4)

OscarRyz
OscarRyz

Reputation: 199215

You don't have braces so the while loop cycles through the System.out.print statement and never exists.

If you add the braces as it is you will fail at reading an int when a non/integer is entered.

To properly read an integer you have to loop asking for the next token, and then verifying it was an int.

$cat Wt.java
import java.util.*;

class Wt {
    public static void main( String ... args ) {
        Scanner s = new Scanner(System.in);

        System.out.print("Write a number: ");
        while ( !s.hasNextInt()) {
             System.out.print("Write a number: ");
             s.next(); // <-- ask for the next and see if that was an int
        }
        int n = s.nextInt();
        System.out.println("The number was: " + n );
    }
}

$javac Wt.java
$java Wt
Write a number: one
Write a number: two
Write a number: tres
Write a number: 1.1
Write a number: f
Write a number: 42
The number was: 42

Upvotes: 0

thegrinner
thegrinner

Reputation: 12243

Your while loop isn't actually consuming what it sees. You need to consume the non-integer input:

while (!scan.hasNextInt()) {
    System.out.print ("reenter as integer: ");
    scan.next(); // Consumes the scanner input indiscriminately (to a delimiter)
}

num = scan.nextInt(); // Consumes the scanner input as an int

Upvotes: 3

Rohit Jain
Rohit Jain

Reputation: 213213

The Scanner#hasNextInt() method doesn't move the cursor past any input. So, it will keep on testing against the same input which you give and hence will keep on failing if it fails once. So, if you input "abc", then hasNextInt() will keep on testing against "abc", and thus will go into an infinite loop.

You need to use Scanner#next() method inside the while loop for that.

Also, you should consider using some maximum attempt for user to enter correct input, so that this doesn't go into infinite loop if user keeps on passing invalid input.

int maxTries = 3;
int count = 0;

while (!scan.hasNextInt()) {
    if (++count == maxTries) {
        // Maximum Attempt reached.
        // throw some exception
    }

    System.out.print ("reenter as integer: ");        
    scan.next();  // Move cursor past current input
}

num = scan.nextInt();

Upvotes: 3

DwB
DwB

Reputation: 38290

The expression "!scan.hasNextInt()" translates to "there is not another int for which I can scan" Consider looping on "scan.hasNextInt()" which translates to "there is another int for which I can scan"

Upvotes: 0

Related Questions