Let's say I have this code:
public static void main(String[] args)
{
Scanner key01 = new Scanner(System.in);
int input;
System.out.println("Please enter a int.");
while (key01.hasNext())
{
if(key01.hasNextInt())
{
input = key01.nextInt();
System.out.println("Thanks for input!");
}
else
{
System.out.println("You must enter an Int");
key01.next(); //Why does this statement prevent an infinite loop?
//That statement prevents
//the program from constantly printing "you must enter an int"
}
}
}
How does key01.next() prevent the console from constantly printing out the error message?
Your loop is on the condition Scanner.hasNext()
; but your if
checks if it specifically has an int
. Without the call to next()
in the else
, when the pending token is not an int
nothing would consume it; thus causing an infinite loop. Your key01.next()
simply consumes the pending token.
If you implement an infinite loop ( while(true)
), Scanner.next() will throw an NoSuchElementException, when your scanner does not have additional elements. This exception would prevent an endless loop.
Elliot's answer explainswhy next() consumes the pending token; and then if you don't have additional tokens in your (not infinite, because it has a condition that gets false) loop. But this isn't what you've asked in your inline comments...
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.