[英]Error with the try-catch statements
I need help fixing the try-catch statement so that it will handle the exception on the first try. 我需要修复try-catch语句的帮助,以便它将在第一次尝试时处理异常。 At the moment, the exception handler only works on the second user input. 目前,异常处理程序仅适用于第二个用户输入。 I apologize in advance for my terrible wording. 我为我的措辞不佳表示歉意。
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();
}
}
You already have the code written out and all. 您已经写出了全部代码。 Either start the "try" earlier, orsurround the first input with the same exact try catch: 要么更早开始“ try”,要么用完全相同的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();
}
}
I think this is what you want, but if not say... 我想这就是您想要的,但是如果不说...
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!");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.