Reputation: 247
import java.util.Scanner;
public class InputLoop
{
public static void main(String[] args)
{
System.out.println("Enter an integer to continue or a non-integer to finish");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
while(scan.hasNextInt())
{
System.out.println("Enter an integer to continue or a non-integer to finish");
scan.next();
}
}
}
This is the first while loop i've written, and when it runs, I have to input a number twice before it proceeds to print "Enter an integer to continue....." Thanks for any help!
Upvotes: 0
Views: 1353
Reputation: 41200
according to docs - Scanner#hasNextInt
Returns true if the next token in this scanner's input can be interpreted as an int value in the default radix using the nextInt() method. The scanner does not advance past any input.
Upvotes: 2
Reputation: 39698
This would be much better as a do ...while loop. Essentially, it is the same, except you check the condition after you are done.
do
{
System.out.println("Enter an integer to continue or a non-integer to finish");
scan.next();
} while(scan.hasNextInt());
Although if you did it as a while, you could add in a dummy variable to make sure you go through at least once.
Boolean firstTime=true;
while(firstTime==true || scan.hasNextInt())
{
firstTime=true;
System.out.println("Enter an integer to continue or a non-integer to finish");
scan.next();
};
Upvotes: 1