CS 124, Spring 2014
Lab 3: Loops and Branches

This week, you will write your first programs with while loops and if statements. For one of the programs, you will also have to learn about reading from a file using TextIO and a little about arrays. You should start by creating a new folder named lab3 inside your cs124 folder, and cd into that folder. All your work for this lab should be done in the lab3 directory.

You will need a copies of TextIO.java, AdditionQuiz.java, and SecondGraphics.java. You can get these files from the directory /classes/cs124/lab3-files. To copy them on the command line, make sure that you are working in your lab3 directory, and give the command

          cp  /classes/cs124/lab3-files/*  .

Your work for this lab is due next Tuesday, at the beginning of the next lab. You should copy your lab3 folder into your homework folder. Make sure that you do all three exercises.

Don't forget about style!!

Exercise 1: Improved Addition Quiz

In class, we looked at a sample program that administers a 10-question addition quiz to the user. The program makes up random addition problems and asks the user to solve them. If the user gets a problem correct, the program tells them that the answer is correct; otherwise, it tells them the right answer.

You should edit your copy of ArithmeticQuiz.java and improve it by adding the following new features (and note that changing the program will also mean changing some of the comments!).

First, your improved program will give the user two chances to get the problem correct. That is, if their first answer is incorrect, then they get another chance to answer the question. Tell them the correct answer only if they give two incorrect answers.

Furthermore, the program should keep score. Each problem is worth 10 points. If the user gets the correct answer on the first try, they get 10 points for the problem. If the user gets the problem correct on the second try, they get 5 points. If they give two wrong answers, they get zero points. At the end of the quiz, you should tell the user their final score.

For just a little bit of extra credit, you can make the program ask some subtraction problems as well as addition problems. Every time it's going to ask a question, the program will decide whether the question should be a subtraction problem or an addition problem. Note that for a subtraction problem, you should make sure that the answer is not a negative number, and this requires some care when selecting the operands.

Exercise 2: Random Drawing

The program SecondGraphics.java is another example of using Java to draw pictures. In this case, however, the picture is redrawn every five seconds. By incorporating some randomness into the drawing subroutine, you can get a somewhat different picture each time it is redrawn. As it stands, the program is very dull: It just draws a 100-by-100 square at a random location. To add some interest, the color of the square is also selected at random.

For exercise 2, you should edit SecondGraphics.java to make a program that draws a large number of differently colored shapes scattered randomly around the image. You should select the location and the color of each shape at random. You are required to use a while loop to count the shapes. Furthermore, you should draw both circles and squares. Each time you want to draw a shape, you should decide at random whether to draw a circle or a square. You are required to use an if statement to implement this random choice.

Here is a reduced-size picture from my version of the program:

The program already has an example of setting a random color. In my picture, I actually use random "translucent" colors, which means that the shapes are slightly transparent. Here is how you can set a color with a random amount of transparency as well as random amounts of red, green, and blue:

int red, green, blue, alpha;
red = (int)( 255*Math.random() );
green = (int)( 255*Math.random() );
blue = (int)( 255*Math.random() );
alpha = (int)( 255*Math.random() );
g.setColor( new Color(red,green,blue,alpha) );

Another possibility is to use some constant amount of transparency, say alpha = 100.

You can try some other variations in the program, if you want. For example, you could choose a random size for the squares and circles. Or you could use rectangles and ovals instead. However, you must have at least two different kinds of shape. You might try drawing a filled translucent shape, then drawing a border around it in solid opaque color.

Exercise 3: What's Up With "String[] args"???

For this exercise, you will write a program from scratch that uses a while loop and an if statement. But first some information about arrays, command-line parameters, and files I/O. (This assignment is in part an exercise in learning to deal with new information and incorporate it into a program.)


In "public static void main(String[] args)", args is an example of an array. An array is a data structure consisting of a list of items. The items are numbered 0, 1, ..., up to some maximum. In Java the number of items in the array args is given by args.length, and the items themselves are args[0], args[1], args[2], ..., up to args[args.length-1]. Note that the notation for arrays uses square brackets, not parentheses. It is possible to have an array with length zero, which contains no items at all.

The args array in a main routine contains information from outside the program. Specifically, it contains command-line parameters. These are extra words that the user types on the command line after the java command that is used to run the program. For example, if you run a Java program named Words with the command

        java  Words  Able  Baker  Charlie

then in the main routine of that program, args.length will be 3, args[0] will be the string "Able", args[1] will be the string "Baker", and args[2] will be the string "Charlie". Command-line parameters don't have to be actual English words. In fact they can be anything, but if they contain spaces or other special characters, they should be enclosed in quotes. The command-line parameters are always given to the program as values of type String. For many programs, the command-line parameters are supposed to be names of files on which the program will operate.


In fact, the program that you write for this exercise will work with files (in a fairly simple way). You need to be able to read from a file using TextIO. TextIO ordinarily reads input typed by the user, but it is possible to "redirect" the input so that it comes from a file instead. This is discussed in the textbook in Section 2.4.5. To start reading from a file named "data.txt", you would use the following command in your program:

       TextIO.readFile( "data.txt" );

After this command is executed, commands such as TextIO.getln() and TextIO.getlnInt() will read from the file instead of from the user. Input starts at the beginning of the file and proceeds through the file just as if the lines in the file were typed by the user. (TextIO can return to reading user input if you use the command TextIO.readStandardInput(), but you wan't need to do that for this exercise.) Note that if args[0], say, is the name of a file, you can tell TextIO to take its input from that file with the command TextIO.readFile(args[0]).


Now, to the exercise...  Linux has a command named head that can be used to print out the first ten lines of a text file. For example, the command

        head  AdditionQuiz.java

will output the first 10 lines of the file AdditionQuiz.java. Your assignment is to write a Java program Head.java that can be used in the same way. For example, the command

       java  Head  sample.txt

should print out the first 10 lines of a file named sample.txt. Furthermore, the Linux head command can print out a different number of lines. The number of lines can be specified as a command line option before the name of the file. For example,

        head  -20  sample.txt

will print the first 20 lines of the file named "sample.txt." (The command line option looks like the negative number -20, but the "-" just means that you are specifying an option, and the value of the option is actually 20.) Similarly, to print out just the first line, you could say,

        head -1 sample.txt

You should write your Java program to work in a similar way. That is, the command

       java  Head  -20  sample.txt

will print out the first 20 lines of sample.txt, while java Head sample.txt will still print out the first 10 lines. To implement this, you will have to test whether args.length is 1 or 2 to determine whether a command line option is present. If it is, you will have to convert args[0] into a number using Integer.parseInt(args[0]). (The function Integer.parseInt() is discussed in Section 2.5.7.)

Finally, your program should also handle the case where the user leaves the file name out of the command (saying just "java Head"). This is an error, and your program should print an error message and exit.

Your program will crash if the file specified by the user does not exist, or if the file contains fewer lines than the user wants to print, or if the option is not a legal integer. This is OK for now, but for a little extra credit, you can make your program avoid the crash. To do that, look ahead at try..catch statements in Section 3.7.