如何使用扫描程序处理由无效输入(输入不匹配异常)引起的无限循环
2022-09-01 02:01:32
所以,我被困在这段代码中:
import java.util.InputMismatchException;
import java.util.Scanner;
public class ConsoleReader {
Scanner reader;
public ConsoleReader() {
reader = new Scanner(System.in);
//reader.useDelimiter(System.getProperty("line.separator"));
}
public int readInt(String msg) {
int num = 0;
boolean loop = true;
while (loop) {
try {
System.out.println(msg);
num = reader.nextInt();
loop = false;
} catch (InputMismatchException e) {
System.out.println("Invalid value!");
}
}
return num;
}
}
这是我的输出:
插入整数:
值无效!
插入整数:
值无效!
...