59.4k views
1 vote
Please write and submit a Java program called AverageDoubles.java, which calculates and displays the average of up to 100 floating-point numbers entered by the user. To earn full credit, your code must:

A) Print a message to standard output that explains what the program does and how the user should enter their numbers.
B) Create an array of length 100 to hold the numbers.
C) Allow the user to enter their numbers one at a time using Text 10 or Scanner, and keep track of how many numbers are entered.
D) Catch a user's mistake if they enter non-double, and ask them to please try again.
E) Print to standard output how many numbers were entered by the user, and the average of the numbers. This should be done only once, after the user has finished entering their numbers.

1 Answer

4 votes

Final answer:

The Java program 'AverageDoubles.java' allows users to enter up to 100 floating-point numbers, calculates the average, and handles erroneous inputs. It uses a Scanner to obtain user input and an array to store the numbers, and prints out the number of valid entries and the average.

Step-by-step explanation:

AverageDoubles.java Program

The following Java program allows users to input up to 100 floating-point numbers, calculates the average, and handles non-double inputs gracefully. It explains its function to the user, uses an array to store the numbers and displays the number of valid inputs as well as the calculated average.

import java.util.Scanner;

public class AverageDoubles {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double[] numbers = new double[100];
int count = 0;
System.out.println("Enter up to 100 floating-point numbers. Type 'end' to finish inputting.");

while (count < numbers.length) {
System.out.print("Enter a number: ");
if (scanner.hasNextDouble()) {
numbers[count] = scanner.nextDouble();
count++;
} else if (scanner.hasNext("end")) {
break;
} else {
System.out.println("That's not a floating-point number. Please try again.");
scanner.next(); // discard the invalid input
}
}

scanner.close();

double sum = 0;
for (int i = 0; i < count; i++) {
sum += numbers[i];
}

double average = (count > 0) ? sum / count : 0;
System.out.println("You entered " + count + " numbers.");
System.out.printf("The average is: %.2f\\", average);
}
}

User Nimrod Dayan
by
7.5k points