java - 如何在 finally block 中输出变量?

标签 java exception try-catch

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

代码:

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

最佳答案

您已经在 try block 中定义了 grade,因此它的范围仅限于 block 本身。它在 try 之外是不可访问的,例如在 finally 中。

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

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

相关文章:

c# - try catch 捕获 .NET 线程池中的错误

PowerShell 错误记录为空/不正确 'InvocationInfo'

c++ - 忽略 C++ 的 Visual Studio 异常设置

java - 什么会导致我的 Spark Streaming 检查点不完整?

java - 如何解析 cookie 字符串

java - Firestore-检查用户名是否已存在

c++ - 未处理的异常,即使在添加 try-catch block 之后? C++

c# - 让 Single 和 SingleOrDefault 抛出更简洁的异常

java - 如何将带有毫秒的模糊时间戳转换为java日期

python - python 循环中的异常处理