Missing parts of expected output from Java try-catch construct

Viewed 87

Question: Create a program called ValidateThird that inputs a grade number (0-5) from the user. If the input is a valid grade number, the program should print "OK". Otherwise, the program should print the entered value and "is not a valid grade." and prompt a grade number again. The program should keep asking grade numbers until the user enters a valid grade number.

My code:

package chapter1.basic;

import java.util.*;

public class ValidateThird {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in); 
        
        boolean continueInput = true;
        
        do {
            
            try {
                
                System.out.print("Enter grade (0-5): ");
                
                String input1 = input.nextLine();
                
                int grade = Integer.parseInt(input1);
             
                if (grade > 5) {
                    System.out.print(input1);
                    throw new NumberFormatException (); 
                }
                else {
                    System.out.println("OK"); 
                }
                continueInput = false;
            }
            catch (NumberFormatException ex) {

                System.out.println(" is not a valid grade.");
                
            }
        } while(continueInput); 
    }
}

My output:

Enter grade (0-5): 9

9 is not a valid grade.

Enter grade (0-5): two

 is not a valid grade.

Enter grade (0-5): 4

OK

, My expected output:

Enter grade (0-5): 9

9 is not a valid grade.

Enter grade (0-5): two

two is not a valid grade.

Enter grade (0-5): 4

OK

because of the scopes of variables, I could not get input from try to use in the catch. Any idea how to fix my code to generate the expected output?

Thank you in advance!

1 Answers

You can move the variable outside the try-scope to be seen in catch, like this:

    public static void main(String[] args) throws Exception, IOException {
        Scanner scanner = new Scanner(System.in);
        String str = "";
        boolean continueInput = true;

        do {
            try {
                System.out.print("Enter grade (0-5): ");
                str = scanner.nextLine();
                int grade = Integer.parseInt(str);

                if (grade > 5) {
                    System.out.print(str);
                    throw new NumberFormatException();
                } else {
                    System.out.println("OK");
                }
                continueInput = false;
            } catch (NumberFormatException ex) {
                System.out.println(str + " is not a valid grade.");
            }
        } while (continueInput);
        scanner.close();
    }
Related