University of North Carolina at Asheville

CSCI 202: Introduction to Data Structures


Lab 03: Input and Output

[Introduction] [Instructions] [What To Submit]


Introduction

This lab will give you a chance to work with some useful features of input and output in Java programming. These topics are covered in Section 1.5 of your text.

Instructions:

To complete this project, follow the steps listed below:

  1. Login to your home directory and launch a terminal window. Use the cd command to change the default directory to csci/202/labs. For the moment, just leave this window lurking around for future reference, and proceed...
  2. Now launch the NetBeans IDE and select the File/New Project... option in the toplevel menu bar. In the first dialog, define the project to be a Java Application. In the second dialog, name your project Lab03, and make sure that your project folder will be created within your csci/202/labs folder. For this lab, you should also uncheck the Create Main Class checkbox. Recall that we do this whenever we want NetBeans to start us off with nothing more than an empty default package for our project. Otherwise, accept the default settings and click Finish.

    If you want to be especially careful, you should now use the file explorer or your terminal window to verify that your Lab03 project folder is indeed in csci/202/labs. While you are doing so, also note that the source files you will be downloading below should all be placed in the project subfolder Lab03/src/.

  3. Now go to the Booksite. Find the source file RandomSeq.java (Program 1.5.1 in your text), and download it into your Lab03/src/ folder. Remember to download the plain-text versions of these textbook files, not the fancy HTML versions. Within a few seconds after you download it, NetBeans will automatically detect this new file and add it to your Lab03 project.

    Before moving on, you should take the time to list the contents of RandomSeq.java. Hopefully you will have no trouble seeing what this program should do when you run it.

  4. Build the project. This step should cause you no problems, since at this stage you are just compiling an unedited Booksite demo. But if anything goes wrong, check immediately with your lab instructor before proceeding.

    Note that for the next steps, it will not be sufficient merely to compile individual source files. Unfortunately, this is all that happens if you right-click on a source file and select the Compile File option. Instead you must be sure to use the project-wide Build option. This compiles all the source files in your project, and it generates a dist subfolder containing a JAR file named Lab03.jar. We will use this JAR file to run project files from the terminal window, as you have already seen in the lectures.

  5. Now switch back to your terminal window, and set your default directory to be the Lab03 subfolder. Use the ls dist command to list the dist folder contents. You should see the file Lab03.jar. If not, it's again time to consult with your lab instructor. You should also enter the command
    jar tf dist/Lab03.jar
    to examine the contents of Lab03.jar. As you can see, it contains only the bytecode file RandomSeq.class, not the source file RandomSeq.java. But the bytecode is all we need to run this program from a command line.
  6. Enter the command
    java -cp dist/Lab03.jar RandomSeq 10
    You should recall from the lectures that this command invokes the Java Virtual Machine (JVM) to run a main class called RandomSeq, using the command-line argument 10. The -cp option is used to state that the classpath is just the JAR file Lab03.jar. Remember, the classpath is just a list of folders and/or JAR files indicating where the class RandomSeq and any other referenced classes may be found.

    In any event, you should now be staring at a list of 10 random real values in the terminal window.

  7. Your next task is to make RandomSeq write its output to a textfile, rather than the terminal window. To do this, we simply redefine the standard output device associated with the command you entered above, which by default is just the terminal window. This procedure is called redirection and it can be done for standard input (normally the keyboard) as well as standard output. For output, we simply change the command to
    java -cp dist/Lab03.jar RandomSeq 10 > dist/randomseq.txt
    which creates a new textfile named randomseq.txt and makes it the standard output for this invocation of RandomSeq. If you again use ls dist to list the files in the dist folder, you should see randomseq.txt as well as Lab03.jar. You should also use either cat or more to list the contents of randomseq.txt.

    Of course you could choose other names for the output file. You can also supply a complete or relative pathname (not just a base name) to create the file in some other folder. For instance, try

    java -cp dist/Lab03.jar RandomSeq 10 > ../randomseq2.txt
    and then see if you can find the new file randomseq2.txt.
  8. As you already know, the authors of your text have provided a useful library class named StdDraw, which is intended to help you write short programs for drawing graphics. They have also written two other library classes, namely StdOut and StdIn, to help simplify programs using standard input and output. While these classes are not really so different from the current standard Java library classes for I/O, they are used in many of the textbook demo applications. So in this lab you will get a little practice with these libraries, starting with StdOut.

    First you need to get these libraries and make them available to your project. For the purposes of this lab, you can get StdOut, StdIn, StdDraw, and StdAudio all at once if you download the single JAR file Booksite.jar into your csci/202/labs folder. Then, in your NetBeans window, raise the Properties dialog for your Lab03 project, which appears as shown below:

    In the left-hand panel, select the Category Libraries. Then click the button in the right-hand panel labeled Add JAR/Folder. This should raise the dialog

    Use the text box labeled Look in: to browse for the folder where you downloaded Booksite.jar (which ought to be csci/202/labs if you followed the instructions above). Once you see Booksite.jar listed in the main text area, select it and click Open. As you might guess, this adds Booksite.jar to your NetBeans project classpath.

  9. Now go back and edit RandomSeq.java as follows:

    When you have made these changes, Build the project again before proceeding to the next step.

  10. To run the new version, enter the revised command
    java -cp ../Booksite.jar:dist/Lab03.jar RandomSeq 10
    Notice how the command-line classpath has been changed: now we must include not only Lab03.jar, but also Booksite.jar as well. If you look carefully, you will see a colon (:) separating these files. In general, a classpath is a list of folders and/or JAR files, separated either by a colon (Unix/Linux) or a semicolon (Microsoft).

    Hopefully you now see the same sort of display in the terminal window that the original version produced...

  11. The authors wrote StdOut in order to simplify the task of producing standard output, especially formatted output. In particular, StdOut has a printf() method similar to one developed long ago for C programmers. An example is shown below:
    StdOut.printf("%7.5f\n", Math.random());
    This statement prints a single random value on a line, just like the println() statement in RandomSeq.java. But it prints the value using a format specifier string that specifies the total number of character spaces used to display it (7 in this case), as well as the number of digits shown after the decimal point (5).

    Try out this feature now, by replacing the println() statement in RandomSeq by the printf() version as written above. Rebuild the project and run RandomSeq to see the formatted values. We will use the new version for the rest of this lab.

    Note: As of Java 1.5 there is a standard System.out.printf() statement, which is quite similar to the textbook StdOut version.

  12. Now we turn to a program that requires data from standard input (which by default is your keyboard). Return to the Booksite and find the source file Average.java (Program 1.5.3 in your text). Download this source (again, the plain-text version) into your Lab03/src/ folder. Edit this file so that it includes the statement
    import stdlib.*;

    Before you proceed, take a moment to list this program and try to figure out what it does. Then Build your Lab03 project yet again.

    Now return to the terminal window, and enter the command

    java -cp ../Booksite.jar:dist/Lab03.jar Average
    Note that nothing seems to happen at first. That is because this program is waiting for you to provide the standard input stream it is looking for. This will happen only when you start entering data from the keyboard. In this case, you want to supply a sequence of real numbers, separated from each other by whitespace (blanks, tabs, newlines -- but no commas or other punctuation marks). For keyboard input, you will "end" this stream whenever you type ctrl-D (Unix/Linux) or ctrl-C (Microsoft).

    So... enter, say, 5 values, not all on the same line, and then type ctrl-D. What happens at that point?

  13. Next we redirect the standard input stream, so that the list of real numbers needed by the Average program will be read from a textfile rather than the keyboard. Recall that we just happen to have a suitable textfile lying around, namely the file randomseq.txt generated by RandomSeq in a previous step.

    The command to redirect the input is as follows:

    java -cp ../Booksite.jar:dist/Lab03.jar Average < randomseq.txt 
    So enter this command, and the Average program should immediately read all the numbers in randomseq.txt and write its results to standard output (which in this case is the screen again).
  14. In the last step you saw a case of one program producing output which became the input for a second program. This sort of thing is done so often that Linux and many other operating systems provide a mechanism called piping for "hooking programs together", so that the standard output of one becomes the standard input of another. One simple example of this is the following command:
    cat randomseq.txt | sort
    The first part of this invokes the cat command, which in this case will list the contents of randomseq.txt to its standard output. This is follwed by a vertical bar (|), which represents the pipe that uses this output as standard input to a sort command. As used here, sort treats its standard input as a sequence of lines which it sorts and then passes on to its standard output.

    So enter this command, and see if the results help to clarify all the words you just tried to read...

  15. As a somewhat more long-winded example, try your hand at using the pipe mechanism to have RandomSeq generate 1000 numbers, which Average reads and processes. Let the standard output of Average be the screen, so that when you run this command all you will see is something like the following:

    Number  = 1000
    Average = 0.498597009999994

  16. For your final exercise in this lab, you will need to download a slightly modified version of RandomSeq.java, namely RandomSeq2.java, and add it to your Lab03 project. Rebuild the project and run this version with the input argument 10, then examine its output. As you can see, this version first prints the number N of random values that it will generate. Then it prints a sequence of N lines, with each line containing two numbers. The first is just the loop counter value, while the second is the random value itself. For what follows, you should think of the first value as the index (or subscript) of the corresponding random value in the sequence.

    Now use the textbook StdDraw class (which is also included in Booksite.jar) to write a complete new program named DrawRandomSeq, which reads the output of RandomSeq2 and produces a graphic display similar to the one shown below:

    This display shows N random values (1000 in this example), with each value plotted vs. its index. Thus the x-scale of the plot should be from 0 to N. You can decide for yourself what sort of y-scale works best here.

    Note that the horizontal blue line shown above is just the average of all the random values. For this part you probably want to compute the average directly within DrawRandomSeq.


What To Submit

When your project is complete and working correctly, demonstrate it to your lab instructor. Then, before you exit NetBeans, clean your Lab03 project. Finally, before you logout, switch back to your terminal and set your default directory back to csci/202/labs. Then create a JAR file of your Lab03 project folder, using the command

jar cf Lab03Project.jar Lab03
Please leave Lab03Project.jar in your csci/202/labs directory for the remainder of the semester.