public static void main(String[] args) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
boolean format = false;
int grades = 0;
do {
System.out.println("Enter course mark (0-100): ");
try {
String input = br.readLine();
grades = Integer.parseInt(input);
} catch (NumberFormatException | IOException e) {
System.out.println("Error number format!");
}
} while (!format);
if (grades > 100 || grades < 100) {
System.out.println("Please enter within the range (0-100)");
}
System.out.println("Your grades is " + grades);
}
我在这里做错了什么,我正在努力实现这个目标
Enter course mark (0-100): qwerty
Bad input data type.
Enter course mark (0-100): -12
Input out of [0, 100] range!
Enter course mark (0-100): 24
Your grades is 24
最佳答案
改变
do {
try {
String input = br.readLine();
grades = Integer.parseInt(input);
}
catch(...) { ... }
} while (!format);
至
do {
try {
String input = br.readLine();
grades = Integer.parseInt(input);
format = true; // Add this line
}
catch(...) { ... }
if (grades > 100 || grades < 100) {
System.out.println("Please enter within the range (0-100)");
format = false;
}
} while (!format);
如果执行流程达到format = true;
,则意味着用户的输入是正确的,并且将确保您打破输入循环。
关于java - 使用 try catch 执行 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34077958/