Q1: Design and then implement a program that reads a series of 5 doubles from th
ID: 3924435 • Letter: Q
Question
Q1: Design and then implement a program that reads a series of 5 doubles from the user and prints their average. Read each input value as a string, and then attempt to convert it to a double using the Double.parseDouble method. This method will throw an exception if the parameter given to it cannot be parsed. If this exception occurs (meaning that the input is not a valid number), print an appropriate error message and prompt for the number again. Continue reading values until 5 valid doubles have been entered.
Sample Output:
Explanation / Answer
AverageTest.java
import java.util.Scanner;
public class AverageTest {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double d[]= new double[5];
for(int i=0; i<d.length; i++){
System.out.print("Please enter a number: ");
String s = scan.next();
try{
d[i] = Double.parseDouble(s);
}catch(NumberFormatException e){
System.out.println("Please enter a valid number.");
i--;
}
}
double sum = 0;
for(int i=0; i<d.length; i++){
sum = sum + d[i];
}
double average = sum/d.length;
System.out.println("The average is : "+average);
}
}
Output:
Please enter a number: 5
Please enter a number: 5.5
Please enter a number: number
Please enter a valid number.
Please enter a number: '1
Please enter a valid number.
Please enter a number: 2
Please enter a number: 3.445667
Please enter a number: 1
The average is : 3.3891334
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.