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);
}
我在这里做错了什么我试图实现这个
输入课程标记(0-100):qwerty
输入数据类型错误。
输入课程标记(0-100): - 12
输入[0,100]范围!
输入课程标记(0-100):24
你的成绩是24
答案 0 :(得分:4)
更改
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;
,那么这意味着用户的输入是正确的&amp;将确保你打破输入循环。
答案 1 :(得分:1)
您不需要使用do..while块。可以使用While块本身输出。您也可以像这样更改程序块
public static void main(String[] args) throws IOException
{
int grades = 0;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr)
while((input=br.readLine())!=null)
{
try
{
grades = Integer.parseInt(input);
}
catch (NumberFormatException | IOException e)
{
System.out.println("Error number format!");
}
}
if (grades > 100 || grades < 100)
{
System.out.println("Please enter within the range (0-100)");
}
System.out.println("Your grades is " + grades);
}