gpt4 book ai didi

java - Java抛出了一个我认为不应该的异常

转载 作者:行者123 更新时间:2023-12-03 17:44:32 25 4
gpt4 key购买 nike

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

我要做什么:
它要求一个整数,但是当有人输入字符时,它应该再次询问而不是崩溃。

最佳答案

第二个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.");
}
}
}

关于java - Java抛出了一个我认为不应该的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28877170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com