Lab 2 In-Class: 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 arithmetic operators.

Getting Started

As usual, start Emacs, Firefox, and an xterm window. In the browser go to the class page and open this document. In the xterm, change to your labs directory, create a subdirectory called lab2, and change to that directory.

Variables

A variable is a name for a memory location that holds a value. The value that is stored in this location can be changed, hence the name variable. In Java, a variable must be declared before it can be used. The declaration gives the type of value that will be stored so that the compiler knows how much space to allocate for it. By convention, Java variables start with a lower case letter.

A constant is simply a name for a value. As its name implies, its value cannot be changed. In Java, a constant declaration looks just like a variable declaration except it has the reserved word final in front. By convention, constants are written in all capitals so that they are easily distinguished from variables.

Study the program below, which uses both variables and constants:

 
//*******************************************************************
// File: Circle.java
// Name: 
//
// Purpose: Print the area of a circle with two different radii
//*******************************************************************
 
public class Circle
{
    //-----------------------------------------------------------
    // Print the area of a circle with two different radii.
    //-----------------------------------------------------------
    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

  1. Variable declarations and assignment statements

    Save the circle program, which is in file Circle.java, into your lab2 directory, open it in emacs and 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. In particular, declare both variables first (after the declaration/initialization of the constant PI which should stay the same), then put the two assignment statements to assign values to each variable. Compile and run the program to make sure you did things correctly.

    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 print 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 it 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.

    5. Compile and run the program. 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.

  2. Making the program interactive

    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 having it written into the program ("hardcoded"). Modify your program as follows:

    1. 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.

    2. 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);
      
      
    3. 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. 61 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).

    4. Compile and run your program. Try it with several values. Does your result from above hold?

    5. Formatting your program correctly: By adding the code above you may have messed up the indentation. You can indent a line properly by placing your cursor anywhere on the line then pressing the TAB key OR Emacs will correcly indent if you select the whole program (or region you want indented) using either the mouse or keystrokes (CTRL-x CTRL-p selects the whole emacs buffer, which is the whole program) then use the keystrokes ALT-CTRL-\ (while simultaneously holding down ALT and CTRL hit the backslash key).

  3. Shell Scripts

    A handy system feature 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 (nenscript -2rG filename) by putting the command, slightly modifed (see below), into a file called print (or something else if you prefer) 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 it instead of the whole command. Here are the steps:

    1. In Emacs, open a new file named print in your home directory.
    2. Type the following into the file:
       
                 enscript -2rG $1 
      
      This looks just like the print command you have been using, but it has a $1 instead of the filename. The $1 is an argument, or parameter; it tells the command to use whatever you type after the name of this script file in the place of the $1.
    3. Save your script using C-x C-s.
    4. Go to an xterm and change to your home directory. Type the following command:
       
                 ls -l print
      
      Look at the permissions; you should see that no one has execute permission. To change this, issue the following command:
       
                 chmod a+x print
      
      The Unix command chmod changes the permissions, or mode, of a file. The "a+x" part means for all(a) users, add(+) the execute(x) privilege. The last part (print) is just the name of the file. If you look at the permissions again, you'll see that the file is now executable.

    5. 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.

    6. Using your script: Change to your lab2 directory. Then use the command above to print the file Circle.java using the command
       
      
             ~/print Circle.java
      
      
      If your shell script doesn't work, fix it (ask for help if you need it!).

  4. More variable declarations, assignment statements, and expressions

    The file Paint.java contains the partial program below, 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.

     
    //********************************************************************
    //  File: Paint.java
    //  Name: 
    //
    //  Purpose: Determine how much paint is needed to paint the walls 
    //  (not including the floor or ceiling) of a room given its length, 
    //  width, and height
    //********************************************************************
    
    import java.util.Scanner;
     
    public class Paint
    {
        //----------------------------------------------------------------
        // Determine how much paint is needed to paint a room.
        //----------------------------------------------------------------
        public static void main(String[] args)
        {
    	final double COVERAGE = 350.0;  //paint covers 350 sq ft/gal
            //declare integers length, width, and height
    	//declare integers sideWallArea, endWallArea, and totalArea
            //declare double paintNeeded
     
            // Create a Scanner object (named scan)
     
            //Prompt for and read in the length of the room
     
            //Prompt for and read in the width of the room
     
            //Prompt for and read in the height of the room
     
    	//Compute the area of a side wall (running the length 
    	//of the room) in square feet.
     
    	//Compute the area of an end wall (running the width 
    	//of the room) in square feet.
     
            //Compute the total square feet to be painted (4 walls!)
     
            //Compute the amount of paint needed
     
            //Print the length, width, and height of the room, the total
    	//area, and the number of gallons of paint needed.
     
        }
    }
    
    1. Save this file to your lab2 directory, open it in emacs and put your name in the header documentation.

    2. Fill in the missing statements (the comments provide a guide) so that the program does what it is supposed to.

    3. Compile and run the program and correct any errors.

    4. Print your Paint.java to turn in. (Use your print script!)

  5. 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.

    1. Save the program to your lab2 directory, open it in emacs and study it noting the following:
      • The program currently takes the amount of the purchase and the amount of cash tendered as input. It then computes the amount of change to be returned to the customer. The goal is to have the program break that change down into the number of dollars, the number of quarters, the number of dimes, the number of nickels, and the number of pennies (using the smallest number of coins) to be returned.
      • Note that the number of dollars is already computed - it is the integer part of the change and that is computed by casting the double value in the variable totalChange to an int (using the cast operator (int)). (Casting is discussed on page 57 in the text.)

    2. Compile and run the program to see if the output matches what you would expect. You may see some strange results (if you don't try some different input values). These are due to the way Java works with floating point numbers - roundoff error occurs in the storage and processing of these numbers. We'll learn more about this later and learn how to format the output so things don't look so bad.

    3. Now add to the program as follows:
      • Put your name in the header documentation!
      • Add an assignment statement to compute the number of cents left over and store it in the variable cents that has already been declared. (So if total change is 13.79 then the number of dollars is 13 and the number of cents is 79 - an int).
      • Add a statement to print the number of cents after the number of dollars.
      • Compile and run what you have so far to make sure it is correct.
      • Now add code to break the number of cents down into the number of quarters, dimes, nickels, and pennies. You will need to declare variables for each of these, write assignment statements to compute each, and print statements to print the results. Note that in your calculations integer division (the / operator with integer operands) and the remainder operator (%) come in handy. It would be a good idea to add code for one calculation at a time and check your results before going on. Also you should declare a variable to be used during your calculation to store the number of cents you haven't yet broken down (so it starts as the total number of cents then after you figure out how many of one coin it becomes the number of cents left, and so on). Which value should you compute first - quarters, dimes, nickels, or pennies?.

    4. Be sure your name is in the header documentation and that the program is correctly indented (CTRL-ALT-\)then print your Change.java program to turn in.

Submission