我尝试捕捉以防止输入不匹配。我是java的新手,可能缺少对方法的一些理解。每当我把try catch它给我一个关于必须创建一个返回类型的错误,即使我已经在finally块中。如果我把它保留在try块中,它说我需要一个返回类型。继承我的代码:
public static double average() {
try{
Scanner avgs = new Scanner(System.in);
System.out.println("Enter total number of numbers; ");
double tnum = avgs.nextDouble();
double[] nums = new double[(int) tnum];
double sum = 0;
for (int i = 0; i < tnum; i++) {
System.out.println("Enter number " + (i + 1) + " : ");
nums[i] = avgs.nextDouble();
sum += nums[i];
}
System.out.println(" ");
System.out.println("The sum is: " + sum);
double avg = sum / tnum;
System.out.println("The average is: " + avg);
}catch(InputMismatchException e){System.out.println("Enter a number honey:);
}
finally{return avg;}
}
错误:
Enter a for average or s for sum
a
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
avg cannot be resolved to a variable
at com.towerdef.shit.Recursion.average(Recursion.java:78)
at com.towerdef.shit.Recursion.yn(Recursion.java:18)
at com.towerdef.shit.Recursion.main(Recursion.java:31)
答案 0 :(得分:0)
应该是:
public static double average() {
double avg;
try{
并进一步向下:
System.out.println("The sum is: " + sum);
avg = sum / tnum;
System.out.println("The average is: " + avg);
那就行了。正如其他人所说,avg的定义方式只是包含它的try范围本地,即avg在finally块中不可用。