Lab 2: Variables, Expressions and Types

Lab Objectives

  • Create a simple Linux Shell Script
  • Work with declaring, initializing and assigning variables
  • Work with the Scanner class to get user input
  • Understand the implications of some of the arithemetic operators.

Getting Started

Shell Scripts

A handy feature in Linux is the ability to put one or more commands into a file and then execute the file, instead of giving all of the commands directly to the shell. This is called a shell script. For example, we can use a shell script to keep from having to type that long print command (enscript -2rG filename) by putting the command, slightly modifed (see below), into a file called print in your home directory. After changing the permissions on the file to make it executable (text files aren't executable by default), you can refer to this simpler command instead of the more complex version. Here are the steps:

You can now use this script to print from any directory with the following command:
           ~/print filename
This tells it to use the print command in your home directory to print the file.

Using your script: Change to your directory for Lab 1. Then use the command above to print the file Names.java.

On to Java

The class Eclipse preferences file has been updated to fix improper comment formatting. In order to update your eclipse preferences, copy the file RCEclipsePrefs.epf from the home directory of the user cpsc to your home directory (you should remember how to do this from the previous two labs). Then, to load the preferences first launch Eclipse and perform the following:

  1. Use File menu and select the Import option. A new "Import" dialog box will appear.

  2. Open the General option, highlight Preferences and then press Next

  3. Browse for the file RCEClipsePrefs.epf (Remember, it was stored in your home directory) and then click Finish.

Study the program below. At this point, you should understand what is happening in the code and be able to hand trace the execution.

package lab2;

/**
 * Print the area of a circle given its radius.
 * 
 * @author jdoe
 * 
 */
public class Circle
{

   /**
    * Compute the radius of a circle and print it
    * 
    * @param args
    */
   public static void main(String[] args)
   {
      final double PI = 3.14159;

      int radius = 10;
      double area = PI * radius * radius;

      System.out.println("The area of a circle with radius " + radius + " is "
            + area);

   }

}

Some things to notice: Exercises

In the xterm, change to your Labs directory, create a subdirectory called lab2.

  1. Download Circle.java, to your lab2 directory. Launch Eclipse and find the Circle class in the left-most panel (you may need to press F5 to refresh). Double click it to open the file. (Do NOT use File>Open; the program will not run.) Modify it as follows:

    1. Put your name in the header documentation!

    2. Currently each variable is declared and initialized in the same statement. However, often it is easier to read and modify a program in which the variables are declared first, and assignments and calculations are done later. Modify the program by separating the declarations of variables radius and area from their initializations. Specifically, declare both variables first, then put the two assignment statements to assign values to each variable. Run the program to make sure you did things correctly. (Run as Java Application)

    3. The circumference of a circle is 2 times the product of PI and the radius. Add statements to this program so that it computes and prints the circumference for the circle. You will need to do the following:
      • Declare a new variable to store the circumference. Put this declaration immediately after your declaration of area.
      • Compute the circumference and store the value in your new variable. (Decide where this should go in the program.)
      • Add a println statement to print the circumference (clearly labeled, of course).

    4. When the radius of a circle doubles, what happens to its circumference and area? Do they double as well? You can determine this by doubling the radius, then computing the area and circumference again and dividing the new values by the old. To do this you'll need new variables to hold the second area and circumference since you need both areas and both circumferences to see how the value has changed. However, the new radius should be stored in the same variable as the old radius. Modify the program as follows:
      • Add declarations for a new area variable and a new circumference variable. Be sure their names are different from the first area and circumference variables.
      • After you calculate and print the initial area and circumference, assign the radius a value that is twice its original value (note: your assignment statement should work for any value stored in the radius variable, not just 10). Now calculate the area and circumference again -- storing them in the new variables -- and print them.
      • Compute the change in area by dividing the second area by the first area. This gives you the factor by which the area grew. You can print this value directly (by doing the division in a print statement) or store it in a variable and then print it.
      • Compute and print the change in circumference similarly.
      Look at the results. Is this what you expected? It is always important to verify the output of a program using some knowledge of what the answers should be. In this case you can figure out mathematically what the answers should be. Remember that the radius is multiplied by 2. Since the area formula squares the radius how much is the area multiplied by? What about the circumference? If your results aren't correct, check your program and correct it.

    5. In the program above, you showed what happened to the circumference and area of a circle when the radius went from 10 to 20. Does the same thing happen whenever the radius doubles, or were those answers just for those particular values? To figure this out, you can write a program that reads in a value for the radius from the user instead of using literals. Modify your program as follows:
      • At the top of the file after the documentation but before the class declaration, add the line
            import java.util.Scanner;
        
        This tells the compiler that you will be using methods from the Scanner class which is defined in the java.util class library.

      • Add the following statement to create a Scanner object. This should be inside the main method, after the variable declarations but before the calculations.
            Scanner scan = new Scanner (System.in);
        
      • Delete the line that assigns the value 10 to the variable radius and in its place, add the following:
        • A prompt, that is, a print statement that tells the user what they are supposed to do (e.g., "Please enter a value for the radius:")
        • A read statement that actually reads in the value. Since we are assuming that the radius is an integer, this will use the nextInt() method of the Scanner class (see p. 64 for an example).
        Have the user enter only one radius; the program should do the calculation to get the second radius, which will be double the radius the user entered (you may already have this correct but if you "hardcoded" 20 as the radius in the exercise above you need to change that statement).

      • Be sure to format your program (use the keystrokes CTRL-SHIFT-F or the Source/Format option on the menu). It is a good idea to do this routinely when you add code!

      • Run your program. Note that you may need to make the console window active to type in the input. Also note that the cursor does not necessarily appear at the end of the prompt - that's okay, just type in the numbers and it will move to where it belongs! Run the program several times using different values for the radius. Does your result from above hold?

      Make sure the program is properly formatted then print Circle.java to turn in. Use the command

             ~/print Circle.java
      

  2. The file Paint.java contains the skeleton of a program which when complete will calculate the amount of paint needed to paint the walls of a room of the given length and width. It assumes that the paint covers 350 square feet per gallon.

    Save this file to your lab2 directory, open it in Eclipse, put your name in the header documentation and fill in the missing statements to complete the program. NOTE: The existing comments in the program tell you the statements you need. So, to complete the program, add your code directly after each comment to achieve the described operation.

    Run the program and correct any errors.

    Be sure your program is formatted (CTRL-SHIFT-F) then print Paint.java to turn in.

  3. Integer Arithmetic and Data Conversion

    The file Change.java contains a program to compute the amount of change to be returned to a customer after a purchase. Save the program to your lab2 directory, open it in Eclipse and study it noting the following:

    Compile and run the program to see if the output matches what you would expect.

    Now add to the program as follows:

    Be sure your name is in the header documentation and that you have formatted the program then print your Change.java program to turn in.

    Making an archive file

    All of the files that you created for this lab need to be e-mailed to your professor. Rather than attaching separate Java files to the email, we can combine the files into a single archive file and attach this file to the e-mail. In Linux, you can do this using the tar command. tar stands for tape archive, a rather archaic name for this function. To "tar up" everything in your lab2 directory, do the following:

    1. Move to the lab2 directory.
    2. Type the following command:
         tar czf lab2.tgz .
      
      This strange looking command can be understood as follows:
         c -- "create" a file containing the tarred up files
         z -- "zip" this file, that is, compress it so it takes less space
         f --  use the next argument to name this file
         lab2.tgz -- the name to be used for the tar file
         . -- tar up everything in the current directory
      
    When you're done, do an ls and you should see lab2.tgz in your directory.

    What to turn in