System.out.println("\nHow many sticks do you want?");
while(sticks==0){
try{
sticks=startInput.nextInt();
}catch(InputMismatchException e){
sticks=0;
System.out.println("Please enter a valid number.");
}
sticks=startInput.nextInt();
}
我尝试做什么: 它要求一个int但是当有人输入chars时它应该再次询问而不是崩溃。
答案 0 :(得分:3)
第二个sticks=startInput.nextInt();
不在try-catch
块内,因此如果您放置更多字符,它将再次失败。由于您没有自己处理异常,异常会冒出来并最终导致应用程序崩溃。
编辑:根据你的评论,这取决于。假设您希望在用户提供0
作为问题答案的时候关闭您的应用程序,您可以这样做:
System.out.println("\nHow many sticks do you want?");
while(sticks >= 0){
try{
sticks=startInput.nextInt();
}catch(InputMismatchException e){
sticks=0; //Any value which is not 0 will not break your loop. This will be re-populated when the user will supply the number again.
System.out.println("Please enter a valid number.");
}
}
如果您希望您的应用程序停止(这似乎不太可能)来自您的代码:
System.out.println("\nHow many sticks do you want?");
while(sticks==0){
try{
sticks=startInput.nextInt();
}catch(InputMismatchException e){
sticks=0; //The 0 will break your while loop, exiting your application gracefully.
System.out.println("Please enter a valid number.");
}
}
这是可行的:
private static int sticks;
private static Scanner startInput;
public static void main(String[] args) {
sticks = 0;
startInput = new Scanner(System.in);
while (sticks >= 0) {
try {
System.out.println("How many sticks do you want?");
sticks = Integer.parseInt(startInput.nextLine());
} catch (NumberFormatException e) {
sticks = 0; //Any value which is not 0 will not break your loop. This will be re-populated when the user will supply the number again.
System.out.println("Please enter a valid number.");
}
}
}
答案 1 :(得分:0)
似乎你错过了把循环放在这里,检查下面的代码:
while(true){
System.out.println("\nHow many sticks do you want?");
while(sticks==0){
try{
sticks=startInput.nextInt();
}catch(InputMismatchException e){
sticks=0;
System.out.println("Please enter a valid number.");
}
}
}