Java 使用while循环作为输入验证
我试图使用while循环来请求用户在输入不是整数时重新输入 例如,输入为任何浮点或字符串Java 使用while循环作为输入验证,java,Java,我试图使用while循环来请求用户在输入不是整数时重新输入 例如,输入为任何浮点或字符串 int input; Scanner scan = new Scanner (System.in); System.out.print ("Enter the number of miles: "); input = scan.nextInt(); while (input == int) // This is where the probl
int input;
Scanner scan = new Scanner (System.in);
System.out.print ("Enter the number of miles: ");
input = scan.nextInt();
while (input == int) // This is where the problem is
{
System.out.print("Invalid input. Please reenter: ");
input = scan.nextInt();
}
我想不出一个办法。我刚刚介绍了java这里的问题是,如果输入不能被解析为
int
,scan.nextInt()实际上会抛出一个输入不匹配异常
将此作为备选方案:
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of miles: ");
int input;
while (true) {
try {
input = scan.nextInt();
break;
}
catch (InputMismatchException e) {
System.out.print("Invalid input. Please reenter: ");
scan.nextLine();
}
}
System.out.println("you entered: " + input);
javadocs说,如果输入不匹配,该方法将抛出InputMismatchException;与整数正则表达式不匹配。也许这就是你需要的
所以
int输入=-1;
while(输入<0){
试一试{
输入=scan.nextInt();
}捕获(输入不匹配异常e){
System.out.print(“输入无效,请重新输入:”);
}
}
例如。看看扫描仪。hasNext
方法。在这里,您可以确定下一个输入的类型。除了-1可能是一个有效的数字。我下面的答案是可行的。仅供参考:根据编辑和选项卡中的用户设置(即最早的…),下面的“内容”很快就会失去意义。
int input = -1;
while(input < 0) {
try {
input = scan.nextInt();
} catch(InputMismatchException e) {
System.out.print("Invalid input. Please reenter: ");
}
}