2014-06-20 30 views
1

我似乎有这个问题很多,我不能完全似乎明白了如何工作的扫描仪我的扫描仪会要求输入两次

System.out.println("Please enter a number"); 
Scanner choice1 = new Scanner(System.in); 
int choiceH = choice1.nextInt(); 

while(!choice1.hasNextInt()){ 
    System.out.println("Please enter a number"); 
    choice1.next(); 
} 

我想要什么的代码做的就是要求一个数,并检查输入是否是一个数字。 我的问题是,它会问号码两次,我不知道为什么。

回答

0

在线路

Scanner choice1 = new Scanner(System.in); 

缓冲区将是空的。当你到达线

int choiceH = choice1.nextInt(); 

你输入一个数字,然后按Enter键。在此之后,号码将被存储在缓冲区中并被消耗(缓冲区将再次为空)。当你到达线

while (!choice1.hasNextInt()) 

程序会检查是否有在缓冲区中的int,但在这一刻,这将是空的,所以hasNextInt将返回false。所以,条件是true,程序会再次要求int

你如何解决它?您可以删除第一个nextInt

System.out.println("Please enter a number"); 
Scanner choice1 = new Scanner(System.in); 
int choiceH = -1; // some default value 

while (!choice1.hasNextInt()) { 
    System.out.println("Please enter a number"); 
    choice1.nextInt(); 
} 
0

如果这行代码执行成功:

int choiceH = choice1.nextInt(); 

然后用户输入一个int和解析成功。没有理由再次检查hasNextInt()

如果用户没有输入int,那么nextInt()将抛出一个InputMismatchException,您应该简单地捕获它,并再次提示用户。

boolean succeeded = false; 
int choiceH = 0; 
Scanner choice1 = new Scanner(System.in); 

do { 
    try { 
     System.out.println("Please enter a number"); 
     choiceH = choice1.nextInt(); 
     succeeded = true; 
    } 
    catch(InputMismatchException e){ 
     choice1.next(); // User didn't enter a number; read and discard whatever was entered. 
    } 
} while(!succeeded);