而具有hasNextInt()的Loop实际上正在读取吗? [英] While Loop with hasNextInt() actually reading?

查看:50
本文介绍了而具有hasNextInt()的Loop实际上正在读取吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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(); }

在询问输入整数:"后,它应该读入一个int值.之后,只要将整数放入输入中,此过程就会重复.实际上,它会打印出这样的内容:

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: "

这次没有打印消息

输入一个整数:12

Enter an integer: 12

如果我在while循环之前忽略了 integer = in.nextInt(); 代码部分,则一切正常.程序为什么会这样?是因为缓冲还是逻辑错误.

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.

谢谢!

推荐答案

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

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

您可以使用do while循环

you can use a do while loop

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

这篇关于而具有hasNextInt()的Loop实际上正在读取吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆