问题
Hello my problem is with this program.
int integer = 0;
int evenInts = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter an integer: ");
integer = in.nextInt();
while(in.hasNextInt()){
System.out.print("Enter an integer: ");
integer = in.nextInt(); }
It should read in an int after "Enter an integer: " is asked. After that as long as integers are put in the input this procedure gets repeated. Actually it prints something like this :
Enter an integer: 10
10 // so basically the
"Enter an integer: "
message does not get printed this time
Enter an integer: 12
If I leave away the integer = in.nextInt();
code part before the while loop everything works fine. Why does the program behave like this? Is it because of buffering or a logical error.
Thanks!
回答1:
that is because you have used up the only integer in your input stream and the hasNextInt()
returns false because there is no next int in the input stream.
System.out.print("Enter an integer: ");
integer = in.nextInt();// here you have read the int there is no more next int
you can use a do while loop
do{
System.out.print("Enter an integer: ");
integer = in.nextInt();
}while(in.hasNextInt());
回答2:
Put it into a do-while loop:
do{
System.out.print("Enter an integer: ");
integer = in.nextInt();
}while(in.hasNextInt());
Note that the values must be separated by spaces to continue the loop.
来源:https://stackoverflow.com/questions/35633931/while-loop-with-hasnextint-actually-reading