Reputation: 3
I need help fixing the try-catch statement so that it will handle the exception on the first try. 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();
}
}
Upvotes: 0
Views: 109
Reputation: 113
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!");
}
}
}
Upvotes: 2
Reputation: 8338
You already have the code written out and all. Either start the "try" earlier, orsurround the first input with the same exact 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();
}
}
Upvotes: 2