In: Computer Science
Design and implement a program that reads a series of 10 integers from the user and prints their average. Read each input value as a string, then attempt to convert it to an integer using the Integer.parseInt method. If this process throws a NumberFormatException (meaning that the input is not a valid integer), display an appropriate error message and prompt for the number again. Continue reading values until 10 valid integers have been entered.
import java.util.Scanner;
public class ValidAverage {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
double total = 0;
int num;
for (int i = 0; i < 10; i++) {
while (true) {
try {
System.out.print("Enter a number: ");
num = Integer.parseInt(in.next());
total += num;
break;
} catch (NumberFormatException e) {
System.out.println("That's not a valid integer. Try again!");
}
}
}
System.out.println("Average of entered numbers is " + (total/10));
}
}
