Question

I am a beginner at java and for my class we are learning about methods. For my first program I have to write a method and provide a program for: double average(double x, double y, double z) returning the average of the arguments. Here is my program so far

//**METHOD**//

    Scanner in = new Scanner(System.in);

    System.out.println("Enter variable x");
    double x = in.nextDouble();

    System.out.println("Enter variable y");
    double y = in.nextDouble();

    System.out.println("Enter variable z");
    double z = in.nextDouble();

    double average;
    System.out.println("The average is: " + average);

//TEST PROGRAM//

    public static double average(double x, double y, double z)
    {
       double average = (x * y * z)/3;
       return average;
    }

No correct solution

OTHER TIPS

A method is only useful if you use it. You will want to reference (or call) the method where you want to use it.

In your code:

System.out.println("The average is: " + average(x, y, z) );

And to clarify, the average is the sum of all values divided by the number of values.

In this case it would be (x + y + z) / 3 not (x * y * z) /3

double average = (x * y * z)/3;
//                  ^   ^ what?

Here's your first problem. Why are you multiplying?

double average;
System.out.println("The average is: " + average);

Your second problem is that you didn't actually call the method. If you just define a method and don't call it, Java doesn't know when you want it called or what arguments you want to use. Defining a variable with the same name doesn't implicitly call the method or anything like that. The method won't run at all. Call it with the arguments you want to get a value:

System.out.println("The average is: " + average(x, y, z));

You also need your code to exist within a class and it will need a public static void main(final String[] args) {} method in order to run.

Call the method like this:

double average = average(x, y, z);
System.out.println("The average is: " + average);

And for the record, the average is the sum of the terms divided by the number of terms, not the product. So change your average method to this:

public static double average(double x, double y, double z)
{
   double average = (x + y + z) / 3;
   return average;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top