SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Exception Handling
Exercise:
Programming Projects
Question:1 | ISBN:9780132830317 | Edition: 5

Question

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


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

import java.util.Scanner;
import java.util.InputMismatchException;
public class TestDemo 
{
	public static void main(String args[]) 
	{
		double total = 0, N, userInput;
		Scanner input = new Scanner(System.in);
		while (true)
		{
		 System.out.print("Enter how many numbers(N) to calculate average:");
		 userInput = input.nextDouble();
		  if (userInput > 0)
		  {
			N = userInput;
			break;
		  } 
		  else
				System.out.println("N must be positive.");
		}
		for (int i = 0; i < N; i++) 
		{
			while (true) 
			{
				System.out.print("Enter number:");
				try 
				{
					userInput = input.nextDouble();
					total += userInput;
					break;

				}
				catch (InputMismatchException e) 
				{
					input.nextLine();
					System.out.println("Input must bea number. Try again");
				} 
			} 
		}
		System.out.println("Average: "+ total / N);
	}
}

OUTPUT:

Enter how many numbers(N) to calculate average:-10
N must be positive.
Enter how many numbers(N) to calculate average:6
Enter number:10
Enter number:20
Enter number:40
Enter number:50
Enter number:200
Enter number:60
Average: 63.333333333333336

 

0 0

Discussions

derrickkorku

You could also use this solution:

package ExceptionHandling;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Problem1 {
    public static void averageOfNNumbers() throws InputMismatchException {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter how many numbers to calculate average of:");
        
        int num = sc.nextInt();
        double total = 0;
        
        
        if (num < 0) {
            sc.close();
            throw new InputMismatchException("Nonpositive number provided.");
        }
        
        
        for (int i = 0; i < num; i++) {
            System.out.println("Enter number: ");
            try {
                double n = sc.nextDouble();
                total += n;
            }catch(Exception ex) {
                System.out.println(ex.getMessage());
                i--;
            }
            
        }
        
        sc.close();
        double average = total / num;
        
        System.out.println("The average of the " + num + " numbers entered is " + average);
    }
    
    public static void main(String[] args) {
        try {
            averageOfNNumbers();
        }catch(InputMismatchException ex){
            System.out.println(ex.getMessage());
        }
    }
}
 

Post the discussion to improve the above solution.