CS 1401, Quiz 13

Date: Monday, November 26, 2007
Name (please type legibly, ideally in block letters): ______________________________________________________________________
Class section (9:30 am or 11:30 am):_______________________________

Write a main method that asks the user for a non-negative integer n and returns the average of all the integers from 1 to n. Make sure that a possible division-by-zero exception is caught by an appropriate error message.

Reminder: to compute the average, you need to add up all the integers from 1 to n and then divide the resulting sum by n.

For extra credit: take care of the situation when a user accidentally types in a negative integer. Warning: extra credit will be only given if the main assignment works correctly.


Solution:

public static void main(String[] args){
  Scanner read = new Scanner(System.in);
  System.out.println("Please enter a non-negative number");
  int n = read.nextInt();
  int sum = 0;
  for(int i = 0; i <= n: i++)
    {sum += i;}
  try{
    int average = sum/n;
    System.out.println(average);
  }
  catch(ArithmeticException e){
    System.out.println("An average cannot be determined since it is" +
      " not possible to divide by 0");
  }
}