CS21 Week5 In-Class Exercises For Thursday

If you have not already done so, create a week5 subdirectory in your cs21 subdirectory, and from your week5 subdirectory, copy over Thursday's week5 files:
% cd  
% cd cs21
% mkdir week5
% cd week5
% pwd 
% cp ~newhall/public/cs21/week5/ArrayExample.java .   
% cp ~newhall/public/cs21/week5/Makefile .   
% cp ~newhall/public/cs21/week5/grade.dat .   

# OR: if you copy over all the files in my week5 subdirectory, then
#     the ATM and Account .java files contain the code that I added
#     in class last time
% cp ~newhall/public/cs21/week5/* .   

  1. We will start by looking at the ArrayExample.java class, and work on the first coupleTODO parts, up until the first:

  2. For programs with large arrays that take input values from the user, it gets very tedious for the user to enter the values over and over again for each run of the program. One way around this is to enter the input values in a file one time, and then have the program read in the values from the file rather than prompting the user to enter them.

    To read in data from a file:

    // we need to add a "throws IOException" clause to the definition
    // of a method that creates a new FileInputStream (we will see what
    // this means later in the semester)
    public static void main(String[] args) throws IOException {
        // reader will read data from the file named infile.dat 
        Scanner reader = new Scanner(new FileInputStream("infile.dat"));
    We could also give the file name as a command line argument. Command line arguments get passed to the main method as an array of String objects, one object per command line argument (String[] args parameter).
    public static void main(String[] args) throws IOException {
        // first check to see if the program was run with the command
        // line argument
        if(args.length < 1) {
            System.out.println("Error, usage: java ClassName inputfile");
        // reader will read data from the file passed as the first
        // command line argument
        Scanner reader = new Scanner(new FileInputStream(args[0]));

  3. Finish TODO parts in the ArrayExample.java file