我试图尽可能地压缩我的代码,并试图在finally中而不是每个case语句中输出变量“ Grade”,但它无法识别该变量。
我觉得解决这个问题的方法太简单了,但我无法一生解决。
谢谢。

码:

public class Grade {//1

public static void main(String[] args) {//2


    ConsoleReader console = new ConsoleReader(System.in);

    boolean done = false;

    System.out.println("Enter your grade percentage:");

    do{
        try{
            int percent = (int) console.readDouble();
            Math.round(percent);
            percent = (int) percent / 10;
            String grade ="Input was not valid";

            if(percent <= 5){//3
                grade = "Your grade is an F, Work Harder so you won't have to retake!";
                System.out.println(grade);
                done = true;

            }else{//3//4
            switch (percent){//5

            case 6:
                grade = "Your grade is a D, work harder";
                System.out.println(grade);
                done = true;

                break;
            case 7:
                grade = "Your grade is a C, That's average but you could do better.";
                System.out.println(grade);
                done = true;

                break;
            case 8:
                grade = "Your grade is a B, That is pretty good but strive for that A";
                System.out.println(grade);
                done = true;

                break;
            case 9:
                grade = "Your grade is a A, Good Work!!";
                System.out.println(grade);
                done = true;

                break;
            case 10:
                grade = "Your grade is a A, Good Work!!";
                System.out.println(grade);
                done = true;

                break;
            default:
                grade = "Your input was invalid, Please enter your grade percentage.";
                System.out.println(grade);
                done = false;

                break;
            }//5
            }//4

        }catch(NumberFormatException e){
            System.out.println("Please input only numbers, try again:");
        }finally{
            if(done == true){
        //ERROR System.out.println(grade); //ERROR
            System.out.println("I hope you're happy with your grade!");
            }else{

            }
        }
    }while(done == false);



    }//2
}//1

最佳答案

您已经在grade块内定义了try,因此它的范围仅限于该块本身的范围。在try外部无法访问,例如在finally中。

要使其在finally中可访问,请在grade块之前声明try,因此其范围是整个方法。

关于java - 如何在finally块中输出变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22308349/

10-12 02:00