While Loop with hasNextInt() actually reading?

五迷三道 提交于 2019-12-24 00:48:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!