Write a Java method to compute the average of three numbers
This Java program prompts the user to enter three numbers and calculates their average. Here's a step-by-step explanation of how the program works:
- The program begins by importing the Scanner class, which is used to read user input from the command line.
- The main method is defined, which is the entry point of the program.
- A new Scanner object is created and assigned to the variable input.
- The program prompts the user to enter the first number by calling System.out.print() method with the message "Enter the Number 1 : ".
- The user enters a value, which is read by calling the nextDouble() method on the Scanner object input, and is assigned to the variable n1.
- The program prompts the user to enter the second number by calling System.out.print() method with the message "Enter the Number 2 : ".
- The user enters a value, which is read by calling the nextDouble() method on the Scanner object input, and is assigned to the variable n2.
- The program prompts the user to enter the third number by calling System.out.print() method with the message "Enter the Number 3 : ".
- The user enters a value, which is read by calling the nextDouble() method on the Scanner object input, and is assigned to the variable n3.
- The program calculates the average of the three numbers by adding them up and dividing by 3, and then prints the result by calling System.out.print() method with the message "The Average value : " concatenated with the result of the calculation, which is enclosed in parentheses.
- The program terminates.
Overall, this program is a simple example of how to use the Scanner class to read user input and perform basic calculations in Java.
Source Code
import java.util.Scanner;
public class Average_ThreeNumbers
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the Number 1 : ");
double n1 = input.nextDouble();
System.out.print("Enter the Number 2 : ");
double n2 = input.nextDouble();
System.out.print("Enter the Number 3 : ");
double n3 = input.nextDouble();
System.out.print("The Average value : " + ((n1 + n2 + n3) / 3 ));
}
}
Output
Enter the Number 1 : 23
Enter the Number 2 : 25
Enter the Number 3 : 7
The Average value : 18.333333333333332