CS 1401 Assignment #7, Solutions

Date Assigned: Monday, March 5, or Tuesday, March 6, 2007.

Due Date: Monday, March 19, or Tuesday, March 20, 2006, before the beginning of your lab section.

Objective: The main objective of this assignment is to learn to design user-defined methods.

Programming assignment: to help compute average grades and student GPAs,

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

Hint:


Solution:

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

public class Assignment7{
  public static double average(String fileName) throws IOException{
    Scanner fromFile = new Scanner(new FileReader(fileName));
    double sum_so_far = 0.0;
    int number_so_far = 0;
    double current_number;

    while(fromFile.hasNext()){
      current_number = fromFile.nextDouble();
      sum_so_far += current_number;
      number_so_far++;
    }
    fromFile.close();

    return sum_so_far / number_so_far;
  }

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

For extra credit: programming assignment 4 from p. 438 of the book.

Homework assignment: on a separate sheet of paper, solve Ex. 2, 4, and 8 at the end of Chapter 7 (on pp. 429 and 431).

Deliverables: as instructed by your TA.