Hi,
I have recently started Java in my course and I have been asked to write a program that finds the sum and average of 5 numbers.
Its very close to working correctly but I cannot see where I am going wrong.

Code:

import java.util.Scanner;

public class average {
	static int i=0;
	static double sum = 0;
	static double average = 0;
	
	public static double calcSum(double sum){	
		double count;
		
		Scanner input = new Scanner(System.in);
		while(i < 5){
			count = input.nextDouble();
			sum = sum + count;
			i++;
		}
		return sum;	
	}

	public static double calcAverage(double average){
		double sum = calcSum(sum);
		average = calcSum(sum) / 5;
		return average;
	}

	public static void main(String[] args) {
		System.out.println("Please enter 5 numbers.");
		System.out.println("Sum is: "+calcSum(sum));
		System.out.println("Average is: "+calcAverage(average));
	}
}

Any help would be appriciated :).

1. You are calling calcSum 3 times (lines 21, 22, 28). You should only call it once (line 28).
2. On line 22 you should just refer to the static sum variable rather than calling calcSum again.
3. Since you have sum as a static variable, you don't need to pass it into calcSum. (Same with average being passed into calcAverage.) Both calcSum and calcAverage should take no arguments.

There are other ways to solve the problems you are having, but this is one way.

Thanks a million! I can see clearly where I was going wrong now. The program now runs perfectly:D

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.