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

Java throws out an exception where I think it shouldnt

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 时,它应该再次询问而不是崩溃。

第二个 sticks=startInput.nextInt(); 不在 try-catch 块内,因此如果您放置更多字符,它将再次失败。由于您没有自己处理异常,异常会冒泡并最终使您的应用程序崩溃。

编辑:根据您的评论,视情况而定。假设您想关闭您的应用程序 when/should 用户提供 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.");
            }
        }
    }

似乎你没有在这里放一个循环,检查下面的代码:

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