我正在尝试尽可能地压缩我的代码,并尝试在 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/