我需要帮助修复try-catch语句,以便它在第一次尝试时处理异常。目前,异常处理程序仅适用于第二个用户输入。我提前为我可怕的措辞道歉。
class MyGradeLevels {
public static void main(String[] args) {
System.out.println("Please enter your grade to begin!");
java.util.Scanner input=new java.util.Scanner(System.in);
double grade=input.nextInt();
if ( grade >= 90 ) {
System.out.println("Great Job!");
} else if( grade <= 49 ) {
System.out.println("Needs Improvement!");
} else {
System.out.println("Average Effort!");
}
try {
grade=input.nextInt();
System.out.println("Your Final Grade is "+grade);
}
catch( java.util.InputMismatchException e ) {
System.out.println("Please round your number and restart!");
}
input.close();
}
}
答案 0 :(得分:2)
您已经编写了所有代码。要么开始&#34;尝试&#34;早些时候,使用完全相同的try catch:
来覆盖第一个输入class MyGradeLevels {
public static void main(String[] args) {
System.out.println("Please enter your grade to begin!");
java.util.Scanner input=new java.util.Scanner(System.in);
double grade;
try {
grade=input.nextInt();
if ( grade >= 90 ) {
System.out.println("Great Job!");
} else if( grade <= 49 ) {
System.out.println("Needs Improvement!");
} else {
System.out.println("Average Effort!");
}
}
catch( java.util.InputMismatchException e ) {
System.out.println("Your number isn't right.");
}
try {
grade=input.nextInt();
System.out.println("Your Final Grade is "+grade);
}
catch( java.util.InputMismatchException e ) {
System.out.println("Please round your number and restart!");
}
input.close();
}
}
答案 1 :(得分:2)
我认为这就是你想要的,但如果不是......
class MyGradeLevels {
public static void main(String[] args) {
System.out.println("Please enter your grade to begin!");
double grade = 0;
try {
java.util.Scanner input = new java.util.Scanner(System.in);
grade = input.nextInt();
} catch (java.util.InputMismatchException e) {
System.out.println("Please round your number and restart!");
}
if (grade >= 90) {
System.out.println("Great Job!");
} else if (grade <= 49) {
System.out.println("Needs Improvement!");
} else {
System.out.println("Average Effort!");
}
try {
java.util.Scanner input = new java.util.Scanner(System.in);
grade = input.nextInt();
System.out.println("Your Final Grade is " + grade);
input.close();
} catch (java.util.InputMismatchException e) {
System.out.println("Please round your number and restart!");
}
}
}