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:

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

  2. In TestDates.java do the following (as indicated by the comments):

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

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

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

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

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

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

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

  10. 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).

  11. 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 file CoinFlips.java has basically the same loop as above with some extra comments. Do the following.
  1. Save CoinFlips.java to your directory then compile and run it to see how it works.
  2. 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).
  3. Compile and run the program. Test it thoroughly. Print out CoinFlips.java to hand in.

What to Hand In