import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
int x = keyboard.nextInt();
}
}
如何在输入int之前循环上面的代码,直到输入int而不是在输入非int时给出错误?
答案 0 :(得分:2)
Scanner类内置了很多东西,除非你明确地想要捕获错误,否则你不需要做try-catches。
public static int test(){
int number = 0;
Scanner input = new Scanner(System.in);
boolean valid = false;
do{
System.out.print("Please enter an integer: ");
if(input.hasNextInt()){ // This checks to see if the next input is a valid **int**
number = input.nextInt();
valid = true;
}
else{
System.out.print("Not a valid integer!\n");
input.next();
}
}while(valid == false);
return number;
}
答案 1 :(得分:0)
这将尝试运行扫描仪,如果输入不是预期的输入,它将仅重新启动。您可以在其中添加一条消息,我的代码是为了简洁。
import java.util.Scanner;
public class test {
public static void main(String[] args) {
System.out.print("Enter a number: ");
Scanner keyboard = new Scanner(System.in);
try {
int x = keyboard.nextInt();
}
catch (java.util.InputMismatchException e) {
main(null);
}
}
}