我想使用异常处理机制来验证用户输入。
例如,假设我要求用户输入整数,然后他们输入了一个字符。在那种情况下,我想告诉他们他们输入了错误的输入,除此之外,我希望他们提示他们再次读入一个整数,并继续这样做,直到他们输入可接受的输入。
我见过一些类似的问题,但他们不会再次接受用户的输入,他们只是打印出输入不正确。
使用 do-while,我会做这样的事情:
Scanner reader = new Scanner(System.in);
System.out.println("Please enter an integer: ");
int i = 0;
do {
i = reader.nextInt();
} while ( ((Object) i).getClass().getName() != Integer ) {
System.out.println("You did not enter an int. Please enter an integer: ");
}
System.out.println("Input of type int: " + i);
问题:
InputMismatchException
将在第 5 行引发,在检查while
条件的语句达到之前。我确实想学习使用异常处理惯用语进行输入验证。
因此,当用户输入错误时,我该如何 (1) 告诉他们他们的输入不正确,以及 (2) 再次读取他们的输入(并继续这样做,直到他们输入正确的输入),使用 try-catch 机制?
编辑:@Italhouarne
import java.util.InputMismatchException;
import java.util.Scanner;
public class WhyThisInfiniteLoop {
public static void main (String [] args) {
Scanner reader = new Scanner(System.in);
int i = 0;
System.out.println("Please enter an integer: ");
while(true){
try{
i = reader.nextInt();
break;
}catch(InputMismatchException ex){
System.out.println("You did not enter an int. Please enter an integer:");
}
}
System.out.println("Input of type int: " + i);
}
}
最佳答案
在 Java 中,最好只在“异常”情况下使用 try/catch。我会使用 Scanner
类来检测是否输入了 int
或其他一些无效字符。
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
boolean gotInt = false;
while (!gotInt) {
System.out.print("Enter int: ");
if (scan.hasNextInt()){
gotInt = true;
}
else {
scan.next(); //clear current input
System.out.println("Not an integer");
}
}
int theInt = scan.nextInt();
}
}
关于java - 如何验证用户的输入,并在无效时再次读入他们的输入,使用 try-catch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35809206/