Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 而hasNextInt()的循环实际正在读取?_Java_Loops_While Loop - Fatal编程技术网

Java 而hasNextInt()的循环实际正在读取?

Java 而hasNextInt()的循环实际正在读取?,java,loops,while-loop,Java,Loops,While Loop,你好,我的问题是这个程序 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(); }

你好,我的问题是这个程序

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(); }
它应该在询问“输入整数:”后读取一个整数。之后,只要在输入中放入整数,这个过程就会重复。 实际上,它打印出如下内容:

Enter an integer: 10
10 // so basically the 
“输入一个整数:”

这次无法打印邮件

输入一个整数:12

如果我把
integer=in.nextInt()去掉while循环之前的代码部分一切正常。为什么程序的行为是这样的?是因为缓冲还是逻辑错误


谢谢

这是因为您已经用完了输入流中唯一的整数,
hasnetint()
返回false,因为输入流中没有下一个int

System.out.print("Enter an integer: ");
 integer = in.nextInt();// here you have read the int there is no more next int
您可以使用do-while循环

do{
 System.out.print("Enter an integer: ");
 integer = in.nextInt(); 
 }while(in.hasNextInt());

将其放入do while循环:

do{
   System.out.print("Enter an integer: ");
   integer = in.nextInt();
}while(in.hasNextInt());

请注意,值之间必须用空格分隔,才能继续循环。

但是如果hasNextInt()方法返回false,为什么我可以扫描另一个int?10//所以这里的//基本上是下一个int