try-catch 语句出错

Error with the try-catch statements

我需要帮助修复 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();     
    }
}

你已经写好了所有的代码。要么更早地开始 "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();     
    }
}

我想这就是你想要的,但如果不是这样...

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!");
    }

}
}