Lab 7 In-Class: More Selection
This lab is designed to give you more practice writing conditional statements.
As usual, create a subdirectory for the lab, open up the Web version of
this handout in Mozilla, and open emacs.
Exercise #1: Activities at Lake Lazydays
Complete the program Temp.java
that prompts the user for a temperature, then
prints out an appropriate activity as described in #1 of the
prelab. As noted in the prelab, you should use a single cascading if
and should keep your conditions as simple as possible.
Print your final program to turn in.
The Switch Statement
The Java switch statement (p. 223 - 227) is
another conditional statement.
Switch provides a compact, efficient syntax that is useful when you
would otherwise have a cascading if statement in which each
condition checks the value of the same expression. For example, the
if and switch statements below do the same thing -- either could be used
as shown in the program:
System.out.println("Enter size box you want");
int boxSize = scan.nextInt();
double price;
if (boxSize == 1)
{
System.out.println("Small");
price = 2.5;
}
else if (boxSize == 2)
{
System.out.println("Medium");
price = 3.75;
}
else if (boxSize == 3)
{
System.out.println("Large");
price = 5.0;
}
else
price = -1;
|
switch (boxSize)
{
case 1:
System.out.println("Small");
price = 2.5;
break;
case 2:
System.out.println("Medium");
price = 3.75;
break;
case 3:
System.out.println("Large");
price = 5.0;
break;
default:
price = -1;
}
|
if (price > 0)
System.out.println("Price is $" + price);
else
System.out.println("Sorry, we don't have that size");
A few things to note about switch statements:
- The expression you are switching on (boxSize in the example above)
must have an integer or character value. It cannot be a boolean,
floating point, or object.
- The expression is evaluated once and then is matched against
each of the cases, starting at the top. When a case matches, all the
rest of the code including later cases is executed. However,
very often
you will only want to execute the code for a single case. To do this, put a
break statement after the code for that case; this will
break control out of the switch statement, sending it to the
next statement in the program.
- If no other case matches, default always matches (like else
in an if statement).
You will use a switch statement (as well as a nested if) in the next exercise.
Exercise #2: Rock, Paper, Scissors
Program Rock.java contains a skeleton for the
game Rock, Paper, Scissors. Open it and save it to your lab7 directory.
Add statements to the program as indicated by the comments so that the program
asks the user to enter a play, generates a random play for the computer,
compares them and announces the winner (and why). For example, one run
of your program might look like this:
$ java Rock
Enter your play: R, P, or S
r
Computer play is S
Rock crushes scissors, you win!
Note that the user should be able to enter either upper or lower case
r, p, and s. The user's play is stored as a string to make it easy to
convert whatever is entered to upper case.
Use a switch statement to convert the randomly generated integer for
the computer's play to a string.
When your program works, modify it so that if either the user or the
computer does not have a legal play (R,P,S), it prints a message
telling which is wrong (user or computer)
and terminates without playing the game. (Note that this will
mean modifying the switch statement so that if the value is not 0,1, or 2
it assigns a different letter, maybe I for illegal, to computerPlay.
Of course, if the computer's play is illegal that means your statement
that generates the random number is wrong!)
If both plays are ok,
go ahead and print the computer's (legal) play and give the
winner. Think about the condition for this: the user's play
should be R or P or S; if it's not
one of these, there's a problem. Similar reasoning holds for the computer's
play. So the structure of the last part of your program should now
look like this:
if (the computer's play is illegal)
print message
else if (the person's play is illegal)
print message
else
{
print computer play
determine and print winner
}
Print your completed program to turn in.
Exercise #3: Date Validation
In this exercise you will write a program that checks to see if a date
entered by the user is a valid date in the second millenium.
A date will be represented by a Date class.
A skeleton of the Date class
is in Date.java and a skeleton of the
program that uses the class is in TestDates.java.
Open these files
and save them to your lab7 directory.
Do the following to complete the Date class and the program:
- In the validDate method in the Date class add the following
as indicated by the comments (ignore the comment about valid
day for now) in the program:
- An assignment statement that sets monthValid to true if the
month entered is between 1 and 12, inclusive.
- An assignment statement that sets yearValid to true if
the year is between 1000 and 1999, inclusive.
- Change the return statement (which currently just returns true)
to return true if the month and year are valid (and false otherwise).
Note that your return statement should just return a boolean
expression.
- In TestDates.java do the following (as indicated by the comments):
- Write a statement that instantiates the someDay object.
- Write an if statement that prints either a "Date is valid" or
"Date is not valid" message. You need to invoke the validDate
method of the Date class.
- Compile and run the TestDates program to see if it works so far.
Enter some months and years that are not valid and some that are.
- Add a method boolean leapYear() to the Date class that
returns true if the year
is a leap year. Here is the leap year rule: A year is
a leap year if a) it's divisible by 400, or b) it's
divisible by 4 and it's not divisible by 100. Your leapYear
method should have a single return statement that returns the boolean
condition describing a leap year.
- In the if statement in TestDates.java, in the case that the date
is valid add an if to test whether or not the year is a leap year.
Print out an appropriate message (is/is not a leap year).
- Compile and run TestDates.java to test your leapYear method.
Some years that are leap years: 1600, 1996, 1776; some years that aren't:
1998, 1900, 1494.
- In the daysInMonth method in the Date class
add an if statement that
determines the number of days in the month
entered and stores that value in variable numDays. If the month
entered is not valid, numDays should get 0. Note that to figure out
the number of days in February you'll need to check if it's a leap year
(that is, you will need to call the leapYear method).
- In the validDate method add an assignment statement to set
dayValid to true if the day is a valid day in the given month and then
modify the return statement
to return a boolean expression that is true if the date is valid.
- Compile and run TestDates to test your latest changes. Be sure to
test all months to see if the last day in the month is correct.
- Complete the toString method in the Date class
by completing the switch
statement that assigns a name to the month and change the return
statement to return a string for the date in the standard way we
write dates (for example, October 25, 1996).
- Modify the print statements in TestDates to print the Date
object (implicitly using toString) along with the message. For
example, if the date entered is 3, 2, 1993 the message should be
"March 2, 1993 is a valid date." but if 3, 32, 1993 is entered
the message should be "March 32, 1993" is not a valid date."
Test the program thoroughly then print both Date.java and TestDates.java to turn in.
Exercise #4: Flipping a Coin - An Introduction to Loops
Flipping a coin several times and seeing how often it comes up heads
is a repetitive task. To simulate such a task in a computer program
you need a loop. The most basic looping structure in Java is
a while statement. The following is a basic while statement:
int numTimes, count;
System.out.print ("How many times do you want the loop to go? ");
numTimes = scan.nextInt();
// Initialize the loop count
count = 0;
// Here's the loop... It is controlled by the condition count < numTimes
while (count < numTimes)
{
// This is the body of the loop - the statements executed repeatedly
count++;
System.out.println ("Looping... " + count + " time(s)!");
}
// After the loop
System.out.println ("Out of the loop!");
There are three basic parts to a loop:
- The setup, or initialization. This is before the
actual loop and is where variables are initialized in preparation for
the loop.
- The condition which is a boolean expression that controls
the loop. If it evaluates to true, the body of the loop is executed,
and then the condition is evaluated again; if it evaluates to false,
the loop terminates.
- The body of the loop. This is where the work is done. In
the above example the count variable is incremented and a message is
printed.
The file CoinFlips.java has basically the
same loop as above with some extra comments. Do the following.
- Save CoinFlips.java to your directory then compile and run it
to see how it works.
- Now change the program to one that repeatedly flips a coin and counts
the heads and tails. The program needs to use the Coin class defined in
your textbook (pages 213 - 215) and in the file
Coin.java. Save Coin.java to your directory (you don't need to
change it at all). Do the following to CoinFlips.java (as indicated
in the comments in the program).
- Declare and instantiate a Coin object named myCoin
- Before the loop initialize the variable numHeads by setting it to 0.
- In the body of the loop flip the coin (note that you use a
method to do this!).
- After you flip the coin, add an if to determine if the coin is
heads (again - there is a method!). If it is, increment the numHeads
variable.
- Modify the print statement so that it prints out the value of
the Coin object (see the toString method in the Coin class - it
determines what is printed)
along with the count.
For example, if the coin turned up tails on the 3rd flip, it should print the
message "Flip 3 is Tails". Your print statement should directly print
the myCoin object to get the Heads or Tails part of this message.
- After the loop put a print statement that prints out the number of
times the coin was heads AND the percentage of times (so if the coin
turned up heads 12 times in 20 flips it was heads 60% of the time).
- Compile and run the program. Test it thoroughly. Print out CoinFlips.java
to hand in.
What to Hand In
- Printouts of Temp.java, Rock.java, Date.java, TestDates.java, and
CoinFlips.java.
- Tar up your lab7 directory and e-mail it to your instructor at roanoke.edu.
Put cpsc120 lab7 in the subject line.