下面的代码询问用户他/她想要多少赛车手。
while (true) { // loops forever until break
try { // checks code for exceptions
System.out.println("How many racers should" + " participate in the race?");
amountRacers = in.nextInt();
break; // if no exceptions breaks out of loop
}
catch (InputMismatchException e) { // if an exception appears prints message below
System.err.println("Please enter a number! " + e.getMessage());
continue; // continues to loop if exception is found
}
}如果在amoutnRacers = in.nextInt();输入了一个数字,那么代码就会从循环中中断,程序的其余部分也会正常运行;但是,当我输入诸如"awredsf“之类的内容时,它应该会捕获该异常,而它就是这样做的。它没有再次提示用户,而是不断地循环,这对我来说是没有意义的。
在连续循环时,程序会像这样打印:
参加比赛的选手有多少?参加比赛的选手有多少?参加比赛的选手有多少?参加比赛的选手有多少?参加比赛的选手有多少?参加比赛的选手有多少?参加比赛的选手有多少?请输入号码!零,请输入一个数字!零,请输入一个数字!零,请输入一个数字!零,请输入一个数字!零,请输入一个数字!零,请输入一个数字!零..。
我不明白amountRacers = in.nextInt();是怎么回事,为什么用户不能输入一个数字?
发布于 2014-07-21 02:53:54
只需在捕获input.next()后添加InputMismatchException即可。
catch (InputMismatchException e) { //if an exception appears prints message below
System.err.println("Please enter a number! " + e.getMessage());
input.next(); // clear scanner wrong input
continue; // continues to loop if exception is found
}您需要清除错误的输入,哪个扫描器自动不输入。
发布于 2016-03-17 21:07:16
今天我解决了这个问题:-)这是我的代码。我想我能帮上忙
public int choice () throws Exception{
Scanner read = new Scanner(System.in));
System.out.println("Choose the option from the upper list");
int auxiliaryChoiceMenu = 5;
int auxiliaryVariable = -1;
boolean auxiliaryBoolean = false;
while (!auxiliaryBoolean) {
try {
auxiliaryVariable = read.nextInt();
read.nextLine();
} catch (Exception e) {
System.out.println("incorrect data, try again"+e);
read.nextLine();
continue;
}
if (auxiliaryVariable<0 || auxiliaryVariable>auxiliaryChoiceMenu){
System.out.println("incorrect data, try again");
} else {
auxiliaryBoolean = true;
}
choiceMenu = auxiliaryVariable;
}
return choiceMenu;
//choicemenu is a external variable
}发布于 2014-07-21 03:00:04
您可能需要创建一个Scanner类,以便从键盘获得标准输入流。您应该在代码中的某个地方有一个语句,该语句创建一个Scanner类的实例,如:Scanner in = new Scanner(System.in);,所以语句中的“in”变量: amountRacers = in.nextInt();等待并扫描从键盘输入的输入并存储它。
https://stackoverflow.com/questions/24857070
复制相似问题