CS 113 - Computer Science 1

Lab 6

More with methods and Unix redirection

In this lab you will:
  1. Use the Scanner class to read from a file OR the keyboard
  2. Write several methods
  3. Send output into files
Reading this on Oct 27, I think that this lab is really long. Just work for 80 minutes. It did not seem that long over the summer.

Unix IO Redirection

The Unix command line is shockingly powerful. One of the wonderful (IMHO) things you can do at the command line is called "Input/Output redirection". Using this you can have a program read from either the keyboard or a file, and the program does not know which! In a similar vein, you can have a program write to the console or to a file, again without the program knowing, or even being able to know. All of this is done with two innocent characters on the command line: > and <.

Looking first at creating a file using the > character. Recall the unix command cat which just dumps the contents of a file onto the screen. For instance

        cat file
    
If, instead, you put the command
        cat file > file.out
    
this would copy file into file.out because the contents of file would be redirected from the console into file.out. (While amusing, this is not a good way to copy a file, use cp instead.)

cat can also be used to create files from the keyboard as shown next.

    cat > file.txt
Try it! After issuing this command you do not get back the Unix prompt, rather everything you type goes into a file. To stop things going into the file (and get back the Unix prompt) type <CTRL> d.

A similar thing can be done to redirect input into Java programs. In this case we use the < character on the command line. For example, consider the following Java program.

            import java.util.Scanner;

public class FRead {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        while (s.hasNext()) {
            System.out.println(s.nextDouble());
        }
        System.out.println("No more to read");
    }    
}
        
This program uses the Scanner class to read a series of doubles from System.in, which is usually the keyboard.

Copy this program into a Lab6 directory. Compile and run it. Give it input from the keyboard like
    5 6 7 8.0
    7.7
etc. You can tell the program there is no more input by typing <CTRL> d. (Exactly as you told cat there was nothing more.)

Next create a data file named data.txt with a set of numbers in it (maybe use the cat trick to do so). To get the FRead program to read this file rather than the keyboard

    java FRead < data.txt

Finally, we can put this all together and have the program read a file and write to a file, all without the program knowing it is doing so. For instance

    java FRead < data.txt > once.txt
When used in this way, the FRead program does a vaguely useful task if we delete the "no more to read" line from the program. Describe what it does in your email lab submission.

In summary, I think of the redirection characters in this way: the pointy side shows where the information is going, the open side show where the information is coming from.

Java

Today you will write a set of methods to do some calculate some fairly simple statistics.

Part 1

To start, create a new java program called Stats. Into Stats, create a main method and another method called readData. The readData method is based on FRead.java above to read from System.in to fill an array of doubles. The program takes one command line parameter, max, which is an integer. That number is passed to readData to define the maximum number of numbers it should read. The method readData should read from System.in until either there is no more to read or the array is full. Try writing this yourself, or just copy the method below. (Be warned, there is one error in the method below for you to correct.)
        public static double[] readData(int maxRead) {
            double[] res = new double[maxRead];
            Scanner s = new Scanner(System.in);
            int readCount = 0;
            while (s.hasNext() && readCount < maxRead) {
                res[readCount] = s.nextDouble();
                readCount++;
            }
        }    
    

Test

Test what you have done. In the main method, call readData passing it some likely small integer (5?). Then, also in you main method, print the contents of the returned array. Try your program with data that you type at the keyboard (remember to hit <CTRL> d) to stop. Also try it with data from a file.

Part 2

Start by moving the code for printing the array out into its own method called printData (much as you did in last weeks lab).

With that move complete, write a new method called "average" which computes the average of the items in the array, and modify your main method to print the average. After this step, your main method should look like (I chose 6 in ReadData somewhat arbitrarily)

    public static void main(String[] args) {
        int max = Integer.parseInt(args[0]);
        double[] data = readData(max);
        printData(data);
        System.out.println("Average: " + average(data));
    }
Now, given the command
    java Stats 6 < data.txt
where data.txt has the following contents
    1.2 3 5 
8 7.7 42.1
43
999.99
the output of the program will be
1.2
3.0
5.0
8.0
7.7
42.1
Average: 11.166666666666666
The program got a 6 from the command line (Yes you can have command line parameters and redirection) so only the first 6 items in the file were used.

Part 3

Extend your stats collection with a method to get the maximum of an array. Here is a maximum function for you to start with:
    public static double maximum(double[] data) {
        double maxx = 0;
        for (int i = 0; i < data.length; i++) {
            if (data[i] > maxx) {
                maxx = data[i];
            }
        }
        return maxx;
    }

Copy this method into your program. This method has a problem; it only works correctly when the input array has at least one non-negative number. As the final part of the lab, try to fix this problem.

What to hand in

Use your phone to take a picture of VSC screen(s) with your java program. If it does not all fit on one screen, just send one picture. Also, At the end of the Unix section, FRead was said to perform a "vaguely useful task". In one sentence, what is that task? Send the picture and your answer to gtowell@brynmawr.edu