有人可以解释并帮我修复这个程序。
import java.util.*;
import java.io.*;
public class test {
public static void main(String[] args) {
Scanner key = new Scanner(System.in);
boolean clear;
int in = 0;
do {
clear = true;
try {
in = key.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid");
clear = false;
}
} while (clear == false);
String stringIn = Integer.toString(in);
String[] dec = stringIn.split("");
for (int i = 1; i < (dec.length); i++) {
System.out.print(dec[i] + " ");
}
}
}
每当我输入无效输入而不是int时,我的程序会循环“无效”,而不是给出输入in的新值的选项。
问题是如果扫描仪无法以正确的格式找到输入,它将抛出异常而不读取输入。
因为扫描程序没有读取无效的int输入,所以下次调用nextInt
时,它会再次尝试读取无效输入,并且很可能会失败,打印另一个“无效!”
因此,如果找到无效的int,则需要在之后读取输入:
// do this in the catch block:
key.next();
这确保读取下一个标记。
完整代码:
Scanner key = new Scanner(System.in);
boolean clear;
int in = 0;
do {
clear = true;
try {
in = key.nextInt();
} catch (InputMismatchException e) {
System.out.println("Invalid");
clear = false;
key.next();
}
} while (clear == false);
String stringIn = Integer.toString(in);
String[] dec = stringIn.split("");
for (int i = 1; i < (dec.length); i++) {
System.out.print(dec[i] + " ");
}
如果下一个标记无法转换为有效的int值,则此方法将抛出InputMismatchException,如下所述。如果翻译成功,扫描仪将超过匹配的输入。
意思是,如果它不成功 - 它将不会前进并将尝试在非法令牌上一次又一次地执行nextInt
失败。
尝试将next()
添加到异常catch子句中,它应该跳过令牌然后读取下一个令牌。 next()
读取一个字符串,因此它并不真正关心格式化,并允许您提升流中的位置以读取下一个标记。
问题是你在catch中写入控制台,所以当你在try中调用key.nextInt()时,程序会读取你打印到控制台的值,所以解决这个问题的一个简单方法是添加一行喜欢:catch中的key.nextLine(),这将解决您的问题。
如果你会尝试这样的事情:
try{
in = key.nextInt();
Integer.parseInt(in);
}catch(Exception e ){
clear = false;
}