write a Java program to print the sum and average of three numbers.
Answers
import java.util.Scanner;
public class Exercise2 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input the first number: ");
double x = in.nextDouble();
System.out.print("Input the second number: ");
double y = in.nextDouble();
System.out.print("Input the third number: ");
double z = in.nextDouble();
System.out.print("The average value is " + average(x, y, z)+"\n" );
}
public static double average(double x, double y, double z)
{
return (x + y + z) / 3;
}
}
Explanation:
public class Average {
public static void main(String[] args) {
// take two numbers
double num1 = 10;
double num2 = 15;
double num3 = 20;
// declare sum variable
// and initialize with 0
double sum = 0.0;
// declare average variable
double avg = 0.0;
// calculate the sum value
sum = num1 + num2 + num3;
// calculate the average value
avg = sum/3;
// display result
System.out.println("Average: " + avg );
}