Java 我的扫描仪要求输入两次
我似乎经常遇到这个问题,我似乎不太明白如何使用扫描仪Java 我的扫描仪要求输入两次,java,integer,Java,Integer,我似乎经常遇到这个问题,我似乎不太明白如何使用扫描仪 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(); }
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();
}
我想要代码做的是询问一个数字,并检查输入是否是一个数字。
我的问题是它两次询问这个数字,我不知道为什么。如果这行代码成功执行:
int choiceH = choice1.nextInt();
然后用户输入了一个int
,解析成功。没有理由再次检查hasnetint()
如果用户没有输入一个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);
排队
Scanner choice1 = new Scanner(System.in);
缓冲区将为空。当你到达终点时
int choiceH = choice1.nextInt();
while (!choice1.hasNextInt())
输入一个数字,然后按enter键。在此之后,数字将存储在缓冲区中并被消耗(缓冲区将再次为空)。当你到达终点时
int choiceH = choice1.nextInt();
while (!choice1.hasNextInt())
程序将检查缓冲区中是否有int
,但此时它将为空,因此hasnetint
将返回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();
}