在 java 中使用 try catch 输入未匹配控制

input miss match control in java with try catch

我写了这段代码来控制输入,所以用户不能输入除整数以外的任何内容 但问题是:当发生异常时,异常块中的消息不断打印并且永不结束,我能做什么?

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int i=0;
    boolean success = false;
    
    System.out.println("Enter an int numbers :");
    
    while(!success) {//"while loop" will continue until user enters an integer
        try {
            i = scanner.nextInt();
            success=true;//if user entered an integer "while loop" will end, or if user entered another type Exception will occur
            
        }catch(InputMismatchException e) {
            System.out.println(" enter only integers ");
        }
    }
    System.out.println(i);
}

你应该在你的 catch 块中添加 scanner.nextLine();

解释是您需要清除扫描仪,为此您应该使用 nextLine()

” 要清除 Scanner 并在不破坏它的情况下再次使用它,我们可以使用 Scanner class 的 nextLine() 方法,它扫描当前行,然后将 Scanner 设置到下一行以执行任何其他操作新行。

如需更多了解,请访问 link

您的代码将如下所示

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    int i=0;
    boolean success = false;
    
    System.out.println("Enter an int numbers :");
    
    while(!success) {//"while loop" will continue until user enters an integer
        try {
            i = scanner.nextInt();
            success=true;//if user entered an integer "while loop" will end, or if user entered another type Exception will occur
            
        }catch(InputMismatchException e) {
            System.out.println(" enter only integers ");
            scanner.nextLine();
        }
    }
    System.out.println(i);
}

添加scanner.nextLine();在你的 try and catch 块中。像这样

while(!success) {//"while loop" will continue until user enters an integer
        try {
            i = scanner.nextInt();
            success=true;//if user entered an integer "while loop" will end, or if user entered another type Exception will occur
            scanner.nextLine();
            
        }catch(InputMismatchException e) {
            System.out.println(" enter only integers ");
            scanner.nextLine();
        }
    }

你也可以在 finaly 块中只添加一个 scanner.nextLine() ,它应该在 catch

下面