Question

I'm putting in a try catch to prevent input mismatch. I'm new to java and may be missing some understanding of methods. Whenever I put the try catch it gives me an error about having to create a return type even though I already have it in the finally block. And if i keep it inside the try block it says I need a return type. Heres my code:

      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;}

}

The error:

  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)
Was it helpful?

Solution

Should be:

public static double average() {
   double avg;
   try{

and further down:

System.out.println("The sum is: " + sum);
avg = sum / tnum;
System.out.println("The average is: " + avg);

That will do it. As others said, the way avg is defined it is only local to the try scope that encloses it, i.e., avg is not available in the finally block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top