CSC 012

Introduction to Computer Science

 

Summary of 4/15 Lecture


Lab Exercise.  The results of a true-false exam have been coded for input.  The information for each student consists of two pieces of information, a student id number and an answer string.  For example, the data for the first student might look as follows:

0080    FTTFTFTTFT

If the correct answer key is:    FTFFTFFTFT,

then the student got 8 correct answers out of 10.

Write a program that

  1. reads in the correct answer string.  If we all use FTFFTFFTFT, then comparing notes would be easier.

  2. reads in each student's data, one at a time.

  3. after reading in a student's data, computes the number of correct answers for that student.

  4. stores the student's id in one array and the number of correct answers for that student in another array.

  5. after finishing processing the students' data, displays a table on the screen that looks as follows:

Student Identification             Number of Correct Answers
0080                                     8
0340                                     6
etc.

For the purposes of making checking the results easier, why don't we all agree to test the data in the file, test.txt.   You will find my solution in Testing.java.


Input from Files

It would be convenient if we could have the computer retrieve the data directly from the file, rather than asking us to retype the information each time we run the program.  This will require some knowledge of how Java handles this chore.

Input is accomplished in Java through the use of input streams.  In particular, files are viewed as byte streams ending with an end-of-file marker.   So the first task is to convert the byte streams to characters.  The character stream is then buffered (i.e., retrieved into RAM).  From this buffer, each line of input can be extracted as a String.  Finally, the String object can be tokenized and parsed to yield the data type required.   Let's indicate this process as follows:

  1. file (stream of bytes)

  2. FileReader object (stream of chars)

  3. BufferedReader object (buffers input allowing access from RAM instead of file)

  4. readLine() message to Buffered Reader object returns String reference to first line of input

  5. StringTokenizer object divides line of data from step 4 into distinct data items (if needed)

  6. parse each data item to extract data of appropriate data type.

Example.  Write a program that takes input from a file, creates a list of int's and calculates the average.

//File:    AverageFile.java
import CSLib.*;
import java.io.*;
public class AverageFile
{
    public static void main (String [] args)
    {
        int [] list = new int [100];
       
        int k=0;
       
        //Step 1. file (stream of bytes)
        String filename = "ints.txt";
           
        try
        {
            //Step 2. FileReader object (stream of chars)
            FileReader fr = new FileReader(filename); //throws FileNotFoundException
           
            //Step 3. BufferedReader object (buffers input allowing access from RAM instead of file)
            BufferedReader br = new BufferedReader (fr);
       
            //Step 4. readLine() message to Buffered Reader object returns String reference to first line of input
            String line = br.readLine(); //throws IOException
            while (line != null)
            {
                list [k] = Integer.parseInt (line); //Step 6:  parse String (line) to extract int (list [k])
                k++;
                line = br.readLine();
            }
           
            br.close(); //not invoked if throws exception
               
        }
        catch (FileNotFoundException e)
        {
            System.out.println ("The file " + filename + " was not found.");
        }
        catch (IOException e)
        {
        }
       
        OutputBox out = new OutputBox("Averaging List");
        out.setSize(280, 250);
        out.println ("Number");

        NumberList.display (out, list, k);
        out.println ("The average of the list is: " + NumberList.average (list, k));
    }
}

wpe10.jpg (8483 bytes)

Where did that try and catch thing come from?  The construction of FileReader object can result in an error (called an I/O exception in Java).  For example, suppose the file doesn't exist?  Rather than accepting this state of affairs, Java requires the programmer to indicate awareness of the potential disaster and provide a response.  This is accomplished through the use of try-catch clauses.  The potentially offending code is enclosed in the try block while the response code is enclosed in a catch block.  Note that it is not required that the program actually respond to the exception, merely indicate that the programmer is aware of the possibility.  In the above example, should an IOException, e, be "thrown", our catch block is empty indicating that our program will take no action.

You should think of this Java feature as an aid in capturing potential errors and handling them in a way that allows the program to respond in an orderly fashion.


Lab Exercise.  Redo the true-false exam lab from above reading directly from the file test.txt.


Lab Exercise.  Add a class method to the NumberList class

public static int readIntList (String fileName, int [] list)

whose purpose is to input an array of int's, called "list", from a data filed named "fileName".


Lab Exercise.  Write a program to read a file of student records and then output the results to the screen, including the original class list along with the class average.   As a last resort, you can check my results.


 

Back to CSC 012 Home Page