数值异常处理程序java

ryoqjall  于 2022-11-27  发布在  Java
关注(0)|答案(1)|浏览(65)

我想看看输入是否是一个数字,如果不是,重新要求一个数字,但我找不到如何做

System.out.println("Enter three numbers: ");

Scanner sc = new Scanner(System.in);
int n1 = sc.nextInt();
int n2 = sc.nextInt();
int n3 = sc.nextInt();
sc.close();
int smallest;
            
if(n1<n2) {
    if(n3<n1) {
        smallest = n3;
    } else {
        smallest = n1;
    }
} else {
    if(n2<n3) {
        smallest = n2;
    } else {
        smallest = n3;
    }
}
    
System.out.println("The smallest number is: " + smallest);

我试了一些方法,但没有结果

yv5phkfx

yv5phkfx1#

您只需将用户输入放入try-catch块中,然后捕获nextInt()在用户输入不是有效整数时抛出的InputMismatchException

try (Scanner sc = new Scanner(System.in)) {
     int n = sc.nextInt();
} catch (InputMismatchException e) {

}

相关问题