Code123
Code123

Reputation: 345

Error with averaging program (Java), (Debugging)

Of course I could have simply done everything in the main method, but that wouldn't help me practice the little I know with Java. So I made, or tried to make, an averaging program, where you input three variables, it calculates the average in a different method and returns the end result. Here is my code:

package test;
import java.util.Scanner;

public class testingclass {
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);

        double[] grades = new double[3];
        System.out.println("Enter 3 grades you want to average out: ");
        grades[0] = input.nextDouble();
        grades[1] = input.nextDouble();
        grades[2] = input.nextDouble();

        display(grades);
        System.out.println(average);

    }

    public static double display(double[] x){
        double total = 0;
        for(int counter = 0; counter < x.length; counter++){
            total = total + x[counter];
        }

        double average = total/x.length;
        return average;
    }
}

So I have everything done, but now I don't know where to go, and when I did System.out.println(average); it told me that average wasn't a variable. Can someone help me with this?

Upvotes: 2

Views: 44

Answers (2)

UnknownOctopus
UnknownOctopus

Reputation: 2287

average isn't a local variable in your main method, only in the display method. Use:

System.out.println(display(grades));

Think of it this way, you are calling your display method with display(grades);, which returns the average of the inputted double array. In this case grades is the array to be averaged.

Upvotes: 3

schtever
schtever

Reputation: 3250

You are getting the error because average is local to your display method. Try:

System.out.println(display(grades));

Upvotes: 3

Related Questions