我想看看输入是否是一个数字,如果不是,重新要求一个数字,但我找不到如何做
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);
我试了一些方法,但没有结果
1条答案
按热度按时间yv5phkfx1#
您只需将用户输入放入try-catch块中,然后捕获
nextInt()
在用户输入不是有效整数时抛出的InputMismatchException
。