This is Java class Write a program that calculates the average of N integers. Th
ID: 3937108 • Letter: T
Question
This is Java class
Write a program that calculates the average of N integers. The program should prompt the user to enter the value for N and then afterward must enter all N numbers. Use an array to save the N integers. If the user enters a nonpositive value for N, then an exception should be thrown (and caught) with the message “N must be positive.” If there is any exception as the user is entering the N numbers, an error message should be displayed, and the user prompted to enter the number again.
Explanation / Answer
AverageCalc.java
import java.util.InputMismatchException;
import java.util.Scanner;
public class AverageCalc {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the N value: ");
int n = scan.nextInt();
if(n > 0){
int a[] = new int[n];
for(int i=0; i<a.length; i++){
try{
System.out.println("Enter a positive number #"+(i+1)+": ");
a[i] = scan.nextInt();
}catch(InputMismatchException e){
i--;
System.out.print("Invalid number. ");
scan.nextLine();
}
}
int sum = 0;
for(int i=0; i<a.length; i++){
sum = sum + a[i];
}
double average = sum/(double)n;
System.out.println("Average is "+average);
}
else{
System.out.println("N must be positive");
}
}
}
Output:
Enter the N value: 5
Enter a positive number #1:
4
Enter a positive number #2:
3
Enter a positive number #3:
2
Enter a positive number #4:
o
Invalid number. Enter a positive number #4:
t
Invalid number. Enter a positive number #4:
8
Enter a positive number #5:
9
Average is 5.2
Enter the N value: -5
N must be positive
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.