In: Computer Science
ComputeAverage
Write a class called ComputeAverage what it does: asks the user to enter three double numbers (see examples below), it uses Scanner class to read from standard input each one of the doubles entered by the user. it then prints the average of the three numbers. Suggested steps: 1. prompt the user to enter each of the three doubles by printing. 2. read each of the three doubles using a Scanner. Remember you need to declare a Scanner variable and then use it to call the nextDouble method of Scanner. 3. assign each of the three doubles to its own variable. At this point you have three different variables, each containing one of the doubles entered by the user. 4. compute the average. The average is computed by adding the three numbers and dividing by 3. 6. print the average. Use printf to print the result using only 2 digits after the decimal point. 7. you can run the application by typing: java ComputeAverage
Examples
(user input shown in boldface) % java ComputeAverage Please enter first double: 9 Please enter second double: 9 Please enter third double: 8 The numbers you entered are : 9.0, 9.0, 8.0 The average is: 8.67 % java ComputeAverage Please enter first double: 10 Please enter second double: 12 Please enter third double: 11 The numbers you entered are : 10.0, 12.0, 11.0 The average is: 11.00 %
Code:
import java.util.*;
public class ComputeAverage
{
public static void main(String args[])
//main method
{
Scanner sc=new
Scanner(System.in);
//object creation for scanner
double a,b,c,avg;
System.out.printf("Please enter
first double: ");
a=sc.nextDouble();
//taking first double as input
System.out.printf("Please enter
second double: ");
b=sc.nextDouble();
//taking second double as input
System.out.printf("Please enter
third double: ");
c=sc.nextDouble();
//taking third double as input
System.out.println("The numbers you
entered are: "+a+", "+b+", "+c);
//printing input values
avg=(a+b+c)/3;
//computing average
System.out.printf("The average is
%.2f",avg);
//printing average upto 2
decimal places
System.out.println("%");
}
}