Lab 2 In-Class: Variables, Expressions and Types
Getting Started
As usual, start Emacs, Mozilla, and an xterm. Go to the class page and
open this document in Mozilla. In the xterm, change to your labs
directory,
create a subdirectory called lab2, and change to that directory.
Some System Hints
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:
- In Emacs, open a new file print in your home directory.
- Type the following into the file:
nenscript -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.
- Save your script using C-x C-s.
- 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.
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.
The man pages
Unix has an online manual called the man pages. If there is any
Unix command you would like to know more about, you can look it up in
the man pages just by typing the following to the shell:
man command
It will then display the documentation on command in "more" style, that is, one page at a time -- press space for the next page, q to get out, b to
go back. For example, man ls will give information on the ls
command. Note that commands that aren't standard in Unix
may or may not
have man pages, depending on whether documentation was installed with the
command. Our system, for example, does not have man pages for nenscript.
Use the man pages to answer the following questions:
- What does the -s option to the ls command do?
- What does the diff command do?
On to Java
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: Adrienne Bloss
//Purpose: Print the area of a circle with two different radii
//**********************************************************
public class Circle
{
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:
- The first three lines inside main are declarations for
PI, radius, and area. Note that the type for each is given in these
lines: final double for PI, since it is a floating point constant;
int for
radius, since it is an integer variable, and double for area, since it
will hold the product of the radius and PI, resulting in a floating point
value.
- These first three lines also hold initializations for PI, radius, and
area. These could have been done separately, but it is often convenient
to assign an initial value when a variable is declared.
- The next line is simply a print statement that shows the area for a
circle of radius 10.
Exercises
Save this program, which is in file Circle.java,
into your lab2 directory and modify it as follows:
- Separate the declarations of variables radius and area from their
initializations. While this is ok as it is, sometimes it is easier to
read and modify a program in which the variables are declared first,
and assignments and calculations are done later.
- 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.
- Compute the circumference and store the value in your new variable.
- Add a print statement
to print the circumference (clearly labeled, of course).
- 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 can
(and 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, modify the
radius so that it is twice its original value. 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?
- 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:
- At the very top of the file, add the line
import cs1.Keyboard;
This tells the compiler that you will be using methods from the Keyboard class.
- Delete the line that sets variable radius to 10.
- 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 readInt() method of
the Keyboard class (see p. 102 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.
- Compile and run your program. Try it with several values.
Does your result from above hold?
Print your Circle.java to turn in.
-
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 cs1.Keyboard;
public class Paint
{
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
//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.
}
}
Save this file
to your lab2 directory and do the following:
- Fill in the missing statements (the comments
provide a guide) so that the program does what it is supposed
to. Compile and run the program and correct any
errors.
- Suppose the room has doors and windows that don't need painting.
Ask the user to enter the number of doors and number of windows in the
room, and adjust the total square feet to be painted accordingly. Assume
that each door is 20 square feet and each window is 15 square feet.
Define constants to hold these values.
Print your Paint.java to turn in.
-
Suppose your lab instructor has a somewhat complicated method
of determining your grade on a lab. Each lab consists of two
out-of-class activities -- a pre-lab assignment and a post-lab
assignment -- plus the in-class activities. The in-class work
is 60% of the lab grade and the out-of-class work is 40% of the
lab grade. Each component of the grade is based on a different
number of points (and this varies from lab to lab) -- for example,
the pre-lab may be graded on a basis of 20 points (so a student
may earn 17 out of 20 points) whereas the post-lab is
graded on a basis of 30 points and the in-class 25 points.
To determine the out-of-class grade the instructor takes the total
points earned (pre plus post) divided by the maximum possible
number of points, multiplied by 100 to
convert to percent; the in-class grade is just the number of
points earned divided by the maximum points, again converted to
percent.
The program LabGrade.java (printout attached)
is supposed to compute the lab
grade for a student. To do this it gets as input the number of
points the student earned on the prelab assignment and the maximum
number of points the student could have earned; the number of points
earned on the lab itself and the maximum number of points; the number
of points earned on the postlab assignment and the maximum number of
points. The lab grade is computed as described above: the
in-class and out-of-class grades (in percent) are computed separately
then a weighted average of these is computed.
The program currently assumes the out-of-class
work counts 40% and the in-class counts 60%. Do the
following:
- First carefully hand trace the program assuming the input stream contains
the values 17, 20, 23, 25, 12, 15. Use your printout to
trace the program exactly as it is
written and answer the following questions on the printout:
- Show how the computer will execute the assignment statement
that computes the out of class average for this set of input.
Show how the expression will be evaluated (for example, draw parentheses
showing the order in which the
operations will be performed) and what the result will be.
- Show how the computer will execute the assignment statement
that computes the in-class average. What will the result be?
- Show how the computer will execute the assignment statement that
computes the lab grade.
- Now run the program, typing in the input you used in your trace.
Clearly the output is incorrect! Is it what you expected?
Correct the program. This involves writing the expressions to do the
calculations correctly. The correct answers for the given input should
be an out of class average of 82.857 (the student earned 29 points out
of a possible 35 which is approximately 82.857%), an in-class average
of 92 (23 points out of 25), and a lab grade of 88.34 (40% of 82.857 plus
60% of 92).
Print your corrected LabGrade.java to turn in.
Making a tar file
An easy way to send someone several files at once is to make a tar file.
(Tar stands for tape archive, a rather archaic name for this
function.)
To "tar up" everything in your lab2 directory, do the
following:
- Change to your lab2 directory.
- 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
- Turn in printouts of Circle.java, Paint.java, and LabGrade.java.
Be sure your
name is in the header of each of your programs.
- E-mail your tar file (lab2.tgz)
to your instructor (ingram or bloss) @roanoke.edu.
Remember to put cpsc120 lab2 in the subject of your message.