Write a program that calculates the average of N integers Th

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.

Solution

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:
1
Enter a positive number #2:
2
Enter a positive number #3:
3
Enter a positive number #4:
e
Invalid number. Enter a positive number #4:
5
Enter a positive number #5:
n
Invalid number. Enter a positive number #5:
6
Average is 3.4

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 numbe
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 numbe

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site