我在学校有这个任务,我有想通过结合一个do循环来进一步完成它,但它没有按照它的意图工作。我试图让它重复整个程序直到输入正确,比如说有人输入一个字符串而不是整数然后它会重复该程序。
我该怎么做?
请不要提供更好的编写此程序的方法,因为这是教师正在寻找的内容。我知道有更好的方式来编写它,因为我已经这样做了。
public class Grade {
public static void main(String[] args) {
ConsoleReader console = new ConsoleReader(System.in);
int i = 1;
do {
System.out.println("Enter your grade percentage:");
int percent = (int) console.readDouble();
Math.round(percent);
percent = (int) percent / 10;
String grade ="Input was not valid";
if(percent <= 5){
grade = "Your grade is an F, Work Harder so you won't have to retake!";
System.out.println(grade);
i = 9999999;
}else{
switch (percent){
case 6:
grade = "Your grade is a D, work harder";
System.out.println(grade);
i = 9999999;
break;
case 7:
grade = "Your grade is a C, That's average but you could do better.";
System.out.println(grade);
i = 9999999;
break;
case 8:
grade = "Your grade is a B, That is pretty good but strive for that A";
System.out.println(grade);
i = 9999999;
break;
case 9:
grade = "Your grade is a A, Good Work!!";
System.out.println(grade);
i = 9999999;
break;
case 10:
grade = "Your grade is a A, Good Work!!";
System.out.println(grade);
i = 9999999;
break;
default:
grade = "Your input was invalid, Please enter your grade percentage.";
System.out.println(grade);
i++;
break;
}
}
}while(i != 9999999);
}
}
答案 0 :(得分:0)
我相信,这不符合您的预期:
int percent = (int) console.readDouble();
Math.round(percent);
percent = (int) percent / 10;
Math#round
函数返回一个舍入值,它不会舍入分配给percent
的值。此外,它没有效果,因为没有舍入int
这样的东西。您只能调用该方法,因为Java编译器应用了类型扩展。这很可能会弄乱你的数据。简单地将double
投射到int
并不是转换数据的好方法。
此外,当用户输入无法解析为double的内容时,console.readDouble()
将导致抛出异常。您应该尝试读取try catch
块中处理catch
块中无效输入的值。
答案 1 :(得分:0)
有一个名为Exception handling
的主题,您应该查看
以示例
来说明boolean done = false;
do {
try{
System.out.println("Enter your percentage");
int percent = (int) console.readDouble();
// more code
// if the condition is satisfied then assign done = true;
} catch(InputMismatchException e) {
System.out.println("Please input only numbers");
}
} while(!done);
如果用户输入的不是数字,那么readDouble
方法会抛出异常,在这种情况下会InputMismatchException
。
控件将转到catch
块,并且警告消息将打印给用户,而不执行readDouble
方法之后的任何其他代码。
由于变量boolean
的{{1}}值仍为false,因此将再次执行while循环。