## 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,

• write a method that, given a name of the file with numbers, computes the average of all these numbers, and
• write a program that uses this method.
Test your program on an example of a simple file with 2 or 3 numbers.

Hint:

• first, create a reader to read from the given file;
• read the records (numbers) one by one; as you read each number, add this number to the sum-so-far, and add 1 to the counter (number of records read so far);
• compute the average by dividing the sum of all the records by the total number of these records.

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);
}
}
```