CS 324, Fall 2005, Lab 2 CPSC 124, Fall 2005 Lab 2: "Once-Through" Programs This is the second lab for CPSC 124: Introduction to Programming. In this lab, you will write three short programs. Since we have not yet covered how to do branching and looping in Java, each program will consist of a sequence of commands that runs "once through" from beginning to end. There are really only three types of statements that you can use in such a program: variable declarations that tell the computer about any variables that you want to use in the program, assignment statements that do computations and move data around inside the computer, and subroutine call statements that call subroutines whose definitions are given somewhere else. Because a "once-through" program can call on subroutines that perform complicated tasks, it can actually do some non-trivial things. The subroutines that are called in a main routine can come from several different places: (1) They can be defined in standard classes that are included with every Java system; (2) They can be in other, non-standard classes that you or someone else has written; or (3) They can be defined in the same class with the mainroutine. The three parts of the lab correspond to these three possibilities. The exercises for this lab are due in lab next Tuesday. The programs that you write should be in your cs124 directory, so that they can be tested. Print out each of the three programs, and turn in printouts next Tuesday. You can use a2ps to print the programs. If a program uses very long lines of text that take up more than one line in a2ps, try the command a2pslong instead; it allows lines that extend all the way across the page. Preliminaries: Some File System Operations For this lab, you will need to create a new directory in your account and copy some existing files into the new directory. There are two ways to do this, using either the command line or the GUI. You really should be able to work using either interfaces. Here are instructions for both: ACTION COMMAND-LINE INTERFACE GRAPHICAL USER INTERFACE Access your cs124 directory Open a new console window by clicking on the "Terminal Program" icon at the bottom of the screen or by selecting "System" then "Terminal" then "Konsole" in the Start menu. Change into your cs124 directory using the command cd cs124. Open a new directory window by clicking the "Home" icon at the bottom of the screen or by selecting "Home" from the Start menu. Click on the cs124 directory to open it. Create a new directory named "lab2" inside the cs124 directory The command for creating a new directory is mkdir. To create the directory named lab2 in the current directory, just use the command mkdir lab2. Then, to change into the lab2 directory, enter cd lab2. Right-click in the directory window that shows the contents of your cs124 directory. You will get a pop-up menu. Go to "Create New" than "Folder...". In the dialog box that appears, enter lab2 as the folder name and click "OK" (or just press return). Then click the "lab2" icon to enter that directory. (Note that the term "folder" means the same thing as "directory".) Copy some files from /classes/s06/cs124 To see what files are in /classes/s06/cs124, you can use the ls command, which lists the contents of a directory: ls /classes/s06/cs124. You will see files named "BadGraphics.java" and "TextIO.java". You want to copy both of these files into the lab2 directory where you are working. Use the command: cp /classes/s06/cs124/* . The "*" is a shorthand way of referring to all the files at once -- you can replace it with an individual file name. The "." at the end is part of the command and refers to the directory that you are currently working in. Open a second directory window by clicking the "Home" icon again. Into the location box at the top, type /classes/f06/cs124 and press return. You will see the contents of the directory. Drag the file icons from that directory to the lab2 directory. When you release the mouse, you will get a pop-up menu asking whether you want to "Copy", "Move", or "Link" the file. Click on "Copy". You can also copy files as follows: Right-click the icon of the file that you want to copy, select "Copy" from the pop-up menu. Then right click the window to which you want to copy the file, and select "Paste" from the pop-up menu. (Note: The two files that you need are also available through the following links: TextIO.java and BadGraphics.java.) Part 1: Computations and Output Besides the basic arithmetic operations (+,-,*,/), you can use functions to do more complex computations in assignments. A function is just a subroutine that computes a value. Several mathematical functions are available in a standard class named Math. Since these functions are defined in a standard class, you can use them in any program. Since they are static members of the Math class, their names begin with "Math.". For example, the function Math.sqrt is used to compute the square root of a number. The number is a "parameter" to the subroutine, such as the 2.0 in "Math.sqrt(2.0)". The parameter can be any number, variable, or even a more complex mathematical expression. Math.sqrt can be used as the right-hand side of an assignment statement: y = Math.sqrt(x); computes the square root of the value of the variable x and stores the answer as the value of the variable y. Math.sqrt can also be used as part of a more complex expression. Another useful function is Math.random(). This function has no parameters, and its value is a random number in the range 0.0 to 1.0 (including 0.0, but not including 1.0). If you need a random number, you can just say "x = Math.random();" to obtain a random number and store it in the variable x. We have also seen the built-in subroutines System.out.print and System.out.println. (The difference between them is that System.out.println(xxx) adds a carriage return after printing out xxx; System.out.print(xxx) does not do this.) These subroutines can be used to output a value to the command line. Since they are defined in standard classes, you can always use System.out.print, System.out.println, and the functions from Math in any program. Exercise 2: The arithmetic mean of two numbers x and y is defined to be (x+y)/2.0. The geometric mean of the same two numbers is defined to be square root of the product x*y. Write a program that makes two random numbers and prints out both numbers, the arithmetic mean of the two numbers, and the geometric mean of the two numbers. The outputs should be labeled as, for example, "First number", "Second number", "Arithmetic mean", and "Geometric mean". Note that you will have to use variables of type double for all the numbers in this program. When you write your program, you can choose any name that you want for it, but remember that if the name of the program is XXXX, then it must be defined in a file named XXXX.java. Part 2: Using TextIO for Input Java does not define input functions, at least none that are convenient for beginning programmers to use. I have written the TextIO class to make up for this deficiency. TextIO defines several functions that can be used for reading values that are typed by the user of the program. Since they are functions, you use them by assigning their value to a variable. The three most useful functions in TextIO are for reading values of type String, int, and double: str = TextIO.getln(); -- If str is a variable of type String, this will stop the program and wait for the use to type in a line of text. The complete line of text that was entered by the user becomes the value of str. n = TextIO.getlnInt(); -- If n is a variable of type int, this will stop the program and wait for the use to type in a line of text. The text is converted into an integer value and is stored in the variable n. (If the user types extra stuff on the line after the number, the extra stuff is discarded.) x = TextIO.getlnDouble(); -- If x is a variable of type double, this will stop the program and wait for the use to type in a line of text. The text is converted into a real number value and is stored in the variable x. (If the user types extra stuff on the line after the number, the extra stuff is discarded.) Once you have the value in a variable, you can use it any way you want in your program. For example, you can use it in computations, and then output the result of the computation back to the user. Now, TextIO is not a standard part of Java, so you can't use it in a program unless you make it available to that program. You can make it available to the program by including TextIO.java in the same directory as the program. Since you have already copied TextIO.java into your lab2 directory, it is available for use in a program that you create in that directory.. (You might notice that when you compile your program the first time, the computer automatically also compiles TextIO.java to give the class file TextIO.class.) Exercise 2: Write a program that has a conversation with the user. Ask the user's name, and then greet the user by name. You could ask the user's birthday, favorite color, a movie they've seen recently. For full credit, do at least one simple calculation with the user's input. For example, ask them what year they were born in, and tell them how old they are. Or ask them how tall they are in inches, and convert their height into feet or meters. Try to use your imagination. The program will use TextIO for input; for output, it can use System.out.print and System.out.println. Part 3: A Bit of (Bad) Computer Graphics The third place where a subroutine can be located is in the same class as the main routine. You won't learn how to write your own subroutines until Chapter 4, but you can still use subroutines that were written by other people. The file BadGraphics.java defines several subroutine for drawing simple shapes. It also includes a main routine that uses some of the subroutines. Compile and run the program to see what it does! This program is your first example of doing graphics in Java. It is "bad" graphics because the way it works is nothing like the "proper" way to do graphics. We will do proper graphics later, but for now, you'll get more experience with using pre-written subroutines, and you'll get some idea of what sort of basic graphics routines are available in Java. To use a subroutine from another class, you have to refer to it by a name of the form ClassName.subroutineName. If the subroutine is defined in the same class, you don't have to mention the class name, so that you can refer to the subroutine with a simple name of the form subroutineName. Here is the information that you need for each subroutine that is defined in BadGraphics.java: setColor(c); -- Sets a color to be used for subsequent drawing operations. For "c", use one of the constant values Color.BLACK, Color.WHITE, Color.RED, Color.GREEN, Color.BLUE, Color.YELLOW, Color.CYAN, Color.MAGENTA, Color.PINK, Color.ORANGE, Color.LIGHT_GRAY, or Color.DARK_GRAY. (If you want to be able to use other colors, ask how to do it!) setFontSize(n); -- Sets the size of the font to be used in subsequent drawStrings. The parameter n should be a positive number. The default size is 12. Larger values will give larger characters and smaller values will give smaller characters. drawString(str,x,y); -- Draws a string with its basepoint at the point (x,y). The string should be in double quotes, as in "Hello World". The basepoint of a string is the left endpoint of a line drawn along the bottom of the string. For x, y, use actual integers in the range 0 to 499. drawLine(x1,y1,x2,y2); -- Draws a line segment from the point (x1,y1) to the point (x2,y2). For x1, y1, x2, and y2, use integers in the range 0 to 499. fillTriangle(x1,y1,x2,y2,x3,y3); -- Draws a filled-in triangle with vertices at the points (x1,y1), (x2,y2), and (x3,y3). The parameters should be integers in the range 0 to 499. drawTriangle(x1,y1,x2,y2,x3,y3); -- Like drawTriangle, but only draws the outline of the triangle. fillRect(x,y,width,height); -- Draws a filled-in rectangle whose upper left corner is at the point (x,y). The parameters should be integers. The width and height are positive integers giving the size of the rectangle, measured in pixels. For a square, use the same value for width and height. drawRect(x,y,width,height); -- Like fillRect, except it only draws the outline around the rectangle. fillOval(x,y,width,height); -- Draws a filled-in oval that just fits inside rectangle that would be drawn by fillRect(x,y,width,height). For a circle, use the same value for width and height. drawOval(x,y,width,height); -- Like fillOval, except it only draws the outline around the oval. The values for the numbers x, y, x1, y1, etc., should be in the range 0 to 499. The drawing takes place in a square that is 500 pixels on a side. The x-coordinate of a point varies from 0 at the left to 499 at the right. The y-coordinate of a point varies from 0 at the top to 499 at the bottom. Exercise 3: Modify the main routine in BadGraphics.java to draw a different picture. While it does not have to be extremely elaborate, it should be significantly more complicated than the picture drawn by the original program. If you can, try to draw something recognizable, such as a snowman, sailboat, house, or truck. You should work only inside the main routine. Do not try to modify or even to read the other subroutine definitions or anything else outside main. David J. Eck, January 2006