【发布时间】:2016-03-05 02:17:31
【问题描述】:
我想使用异常处理机制来验证用户输入。
例如,假设我要求用户输入整数输入并且他们输入一个字符。在这种情况下,我想告诉他们他们输入了错误的输入,除此之外,我希望他们提示他们再次读取整数,并继续这样做直到他们输入一个可接受的输入。
我见过一些类似的问题,但是他们并没有再次接受用户的输入,他们只是打印出输入不正确。
使用 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);
问题:
在检查
while条件的语句到达之前,将在第5 行引发InputMismatchException。我确实想学习使用异常处理习语进行输入验证。
所以当用户输入错误的输入时,我如何 (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 validation input exception-handling