CS 1401 Assignment #12, Solutions

Date Assigned: Monday, April 16, or Tuesday, April 17, 2007.

Due Date: Monday, April 23, or Tuesday, April 24, 2007, before the beginning of your lab section.

Objective: The main objective of this assignment is to learn to handle exceptions.

Programming assignment: add exceptions to our Programming Assignment 7.

Programming Assignment 7: reminder. To help compute average grades and student GPAs,

Test your program on an example of a simple file with 2 or 3 numbers.

Hint:

New part: If the file is empty or if one of the numbers in the file is negative, throw and handle appropriate exceptions -- and inform the user about the problem.

Homework assignment: on a separate sheet of paper, solve Ex. 4 and 6 at the end of Chapter 12 (on pp. 799 and 800).

Deliverables: as instructed by your TA.


import java.io.*;
import java.util.*;

class NegativeException extends Throwable{}
class FileEmptyException extends Throwable{}

public class Assignment7{
  public static double average(String fileName) throws IOException{
    Scanner fromFile = new Scanner(new File(fileName));
    double sum_so_far = 0.0;
    int number_so_far = 0;
    double current_number;
    double average;
    average = -1.0;
    try{
      while(fromFile.hasNext()){
        current_number = fromFile.nextDouble();
        if (current_number < 0)
          {throw new NegativeException();}
        sum_so_far += current_number;
        number_so_far++;
      if (number_so_far == 0)
        throw new FileEmptyException();
        average = sum_so_far / number_so_far;
    }
    catch(NegativeException e){
      System.out.println("One of the numbers in the file is negative,"
        + " so this file cannot be the grades file");
    }
    catch(FileEmptyException e){
      System.out.println("The file is empty, it has no grades at all,"
        + " so it is impossible to compute the average grade");
    }
      fromFile.close();
      return average;
  }
  public static void main(String [] args) throws IOException{
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please enter the name of the file in which you" +
      " keep your records.");
    String file = keyboard.next();
    double av = average(file);
    System.out.println("The average value of the file is " + av);
  }
}