Lab 6: Selection

Instructions: Follow the steps given in each section below. For each question, click the radio button next to the most correct answer. When you are finished, type your name and your partner at the end of the document, write down your answers for your records, then press the Submit button. You may submit just one lab response. If you submit more than one, only the first one counts for a grade.

Contents

A. Purpose

We examined the if and if-else statements in C SC 120. In this lab, we'll examine selection statements in more depth. By the end of the lab, you should be familiar with relational operators, String comparisons, the nested if statement, the dangling-else problem, Boolean operators, and DeMorgan's Laws.

B. Relational Operators

  1. As we saw in C SC 120, we can use an if statement to make the program execute a group of statements when a particular condition is true. We also saw that we can use an if-else statement to execute one of two groups of statements, based on a condition.
  2. Many conditions in if statements and if-else statements are based on a comparison of two values: whether one value is equal, less, or greater than another value. For primitive types (byte, short, int, long, double, float, boolean, char), we can use relational operators to compare values. The six relational operators in Java are:
  3. ==equal to

    !=

    not equal to

    <

    less than

    >

    greater than

    <=

    less than or equal to

    >=

    greater than or equal to

  4. For example, to test whether the integer variable amount is more than 100, you would write
  5. if (amount > 100)
    {
      System.out.println("amount is more than 100");
    }

  6. Notice that the "equal to" relational operator consists of two equal signs, not one. Using one equal sign in Java means assignment or initialization, it is not a test for equality. Usually, the compiler can find this kind of error, but not always. For example, program EqualSigns.java below uses one equal sign instead of two -- in two places. The compiler finds the first error, but not the second.
  7. EqualSigns.javaDownload (Help)
    // Demonstration of incorrect use of = in if statements
    
    public class EqualSigns
    {
      public static void main(String[] args)
      {
        int firstInt = 1, secondInt = 2;
        boolean firstBool = false, secondBool = true;
    
        // The compiler finds this error
        if (firstInt = secondInt)
        {
          System.out.println("The two int variables are equal "
                             + "(1 equals 2)");
        }
    
        // The compiler doesn't find this error
        if (firstBool = secondBool)
        {
          System.out.println("The two boolean variables are equal "
                             + "(false equals true)");
        }
      }
    }
    EqualSigns.javaDownload (Help)

  8. Download program EqualSigns.java and compile it (without fixing the errors).

    Question
    1
    Which lines in program EqualSigns.java generated error messages when you compiled the program?

    1. The first if statement only.
    2. The second if statement only.
    3. Both if statements.
    4. The compiler didn't find any errors.

  9. Fix just the first if statement in EqualSigns.java by changing the single equal sign to two equal signs. (DON'T fix the second error yet!) Save the file and compile it. You should see no error messages. Now run the program.

    Question
    2
    After you fix just the first error, what does EqualSigns.java display when it runs?

    1. nothing
    2. The two int variables are equal (1 equals 2)
      The two boolean variables are equal (false equals true)

    3. The two int variables are equal (1 equals 2)
    4. The two boolean variables are equal (false equals true)

  10. Modify EqualSigns.java so it displays the values of variables firstBool and secondBool after the second if statement.
  11. Question
    3
    What are the values of the variables firstBool and secondBool after the second if statement in EqualSigns.java?

    1. firstBool is false; secondBool is true
    2. firstBool is false; secondBool is false
    3. firstBool is true; secondBool is false
    4. firstBool is true; secondBool is true

  12. Fix the second if statement in EqualSigns.java by changing the single equal sign to two equal signs. Save the file and compile it. You should see no error messages. Now run the program.

    Question
    4
    After you fix the second error, what does EqualSigns.java display when it runs?

    1. nothing
    2. The two int variables are equal (1 equals 2)
    3. The two boolean variables are equal (false equals true)
    4. The two int variables are equal (1 equals 2)
      The two boolean variables are equal (false equals true)

    Question
    5
    After you fix the second error, what are the values of the variables firstBool and secondBool after the second if statement in EqualSigns.java?

    1. firstBool is false; secondBool is true
    2. firstBool is true; secondBool is false
    3. firstBool is false; secondBool is false
    4. firstBool is true; secondBool is true

C. String Comparisons

  1. In Java, the String type is actually a class -- not a primitive type. Therefore, comparing String values with relational operators does not give the result you usually want. For example, the program ControlTurtle.java below is supposed to let you control the turtle by typing in either the word move or turn. The program uses the == operator to compare the user's response with the word move.
  2. ControlTurtle.java Download (Help)
    Download Keyboard (right click and select 'Save Link As...'
    // This program is supposed to let you control the turtle by typing
    // in either the word move or turn. (Wrong!)
    
    import Keyboard;
    import turtlegraphics.*;
    
    public class ControlTurtle
    {
      public static void main(String[] args)
      throws java.io.IOException, TurtleException
      {
        Turtle myTurtle = new Turtle();
        String response = Keyboard.readString("Should the turtle move or turn? ");
    
        if (response == "move")
        {
          System.out.println("Moving ...");
          myTurtle.move(100);
        }
        else
        {
          System.out.println("Turning ...");
          myTurtle.turnRight(90);
        }
      }
    }
    ControlTurtle.java Download (Help)
    Download Keyboard (right click and select 'Save Link As...'

  3. Download ControlTurtle.java, compile it, and run it. Try typing the word move and see what happens, then run the program again and see what happens when you type the word turn.
  4. Question
    6
    Does ControlTurtle.java work correctly?

    1. No, it does nothing.
    2. No, it always turns, no matter what you type.
    3. No, sometimes it moves, sometimes it turns, no matter what you type.
    4. Yes
    5. No, it always moves, no matter what you type.

  5. The reason this program doesn't work is that the == operator, when used with objects (that is, nonprimitive types), tests whether two objects are the same object. The operator does not test whether objects have the same value. In program ControlTurtle.java, the == operator tests whether the word move is the same object as the user's response -- not whether the user's response is equal to the word move. (As you can see, this difference does matter, even though the distinction seems very slight.)
  6. When you want to compare the values of two objects (such as strings) for equality, you should use the equals() method instead of the == operator. Remember that when you use a method, you need to specify the object that contains the method. For example, to check whether the string variable response equals "move", you can write
  7. if (response.equals("move")) ...

    Because the string literal value "move" is also a string, you can use the equals() method on the string literal value instead of the variable. Therefore you can also check whether the string variable response equals "move" like this

    if ("move".equals(response)) ...

    Either way is fine.

  8. Modify ControlTurtle.java so it works correctly, using the equals() method. Compile and run the program to make sure it works.
  9. You can use the equals() method on any object -- strings, turtles, dates, files, etc. The String class also has the compareTo() method that you can use for comparing strings. Unlike the equals() method (which only tells you whether one string contains the same value as another), you can use the compareTo() method to test whether one string is less than, greater than, or equal to another.
  10. Suppose you have to string variables: string1 and string2. The result of string1.compareTo(string2) is:
  11. less than 0-->if the value of string1 is less than string2
    0-->if the two strings have the same value
    greater than 0-->if the value of string1 is greater than string2

    (The Java language, like most programming languages, says that string1 is "less than" string2 if string1 comes before string2 in a dictionary ordering.)

  12. The program DemonstrateCompareTo.java below uses the compareTo() method to compare strings. The program reads two strings from the user, then tells whether the first string is less than, equal to, greater than, not equal to, greater than or equal to, or less than or equal to the second string. The program is incomplete, though.
  13. DemonstrateCompareTo.java Download (Help)
    // Demonstrates use of the compareTo() method.
    
    // Replace each ?? with == 0, != 0, > 0, < 0, >= 0, or <= 0 so the
    // program gives the correct answers.
    
    import Keyboard;
    
    public class DemonstrateCompareTo
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        String string1 = Keyboard.readString("Enter string1: ");
        String string2 = Keyboard.readString("Enter string2: ");
    
        if (string1.compareTo(string2) ??)
        {
          System.out.println(string1 + " is less than " + string2);
        }
    
        if (string1.compareTo(string2) ??)
        {
          System.out.println(string1 + " is equal to " + string2);
        }
    
        if (string1.compareTo(string2) ??)
        {
          System.out.println(string1 + " is greater than " + string2);
        }
    
        if (string1.compareTo(string2) ??)
        {
          System.out.println(string1 + " is not equal to " + string2);
        }
    
        if (string1.compareTo(string2) ??)
        {
          System.out.println(string1 + " is less than or equal to " + string2);
        }
    
        if (string1.compareTo(string2) ??)
        {
          System.out.println(string1 + " is greater than or equal to " + string2);
        }
      }
    }
    DemonstrateCompareTo.javaDownload (Help)

  14. Download DemonstrateCompareTo.java and save it. Using your editor, change each occurrence of ?? with == 0, != 0, > 0, < 0, >= 0, or <= 0 so the program gives the correct answers.

D. Nested if Statements

  1. Briefly, a nested if statement is simply an if statement that contains another if statement. There is no limit to the degree of nesting you can do in Java -- you can put an if statement in another if statement, and put that if statement in another if statement, and so on.
  2. Put an if statement inside another one when you want the an if statement to control the execution of another if statement. That is, you want to base one decision on the result of another.
  3. Program DemonstrateNestedIf.java shows an example of a nested if statement. This program first asks the user whether he or she wants to compare two numbers. The nested (that is, "inner") if statement only compares the two numbers if the user wants this.
  4. DemonstrateNestedIf.javaDownload (Help)
    // Demonstrates use of a nested if statement
    
    import Keyboard;
    
    public class DemonstrateNestedIf
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        char response = Keyboard.readChar("Compare two numbers? (y/n): ", "yn");
        
        if (response == 'y' || response == 'Y')
        {
          int first = Keyboard.readInt("Enter first number: ");
          int second = Keyboard.readInt("Enter second number: ");
    
          // This is the "nested" if statement
          if (first < second)
          {
            System.out.println("The first number is less");
          }
          else
          {
            System.out.println("The first number is not less");
          }
        }
        else
        {
          System.out.println("Ok - but it's your loss!");
        }
      }
    }
    DemonstrateNestedIf.javaDownload (Help)

  5. Download DemonstrateNestedIf.java, then compile and and run the program. Verify that the "inner" if statement only executes if the condition of the "outer" if statement is true.
  6. Question
    7
    Does DemonstrateNestedIf.java work correctly?

    1. Yes
    2. No

  7. One of the dangers of nested if statements is the dangling-else problem. This problem can only arise, however, when you don't use braces around the if-body or else-body. (Recall that you can leave the braces off when the if-body or else-body contains just one statement.)
  8. Program DemonstrateDanglingElse.java below has a dangling-else problem.
  9. DemonstrateDanglingElse.javaDownload (Help)
    // This program has a dangling-else problem
    
    import Keyboard;
    
    public class DemonstrateDanglingElse
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        int year = 0;
    
        int studentStatus
          = Keyboard.readInt("Are you a (1) undergrad or (2) grad? ", 1, 2);
        
        if (studentStatus == 1)
          year = Keyboard.readInt("Are you (1) freshman, (2) soph, (3) jr, (4) senior? ",
                                  1, 4);
        
        // This nested if has a dangling-else problem
        if (studentStatus == 1)
          if (year > 1)
            System.out.println("You're probably glad to be past your first year!");
        else
          System.out.println("Congratulations on being a graduate student!");
      }
    }
    DemonstrateDanglingElse.javaDownload (Help)

  10. Download program DemonstrateDanglingElse.java, then compile and run the program. Try each of the following input data values.
  11. Undergrad or grad? Year
    Test #111
    Test #212
    Test #313
    Test #414
    Test #52n/a

    Question
    8
    Which of the input values don't work correctly when you run DemonstrateDanglingElse.java?

    1. Tests #4 and #5
    2. Test #2
    3. Tests #1 and #5
    4. All tests work correctly
    5. Test #3 and #4

    Question
    9
    The main problem with a dangling-else statement is that the program doesn't run the way it looks like it should. Which of the following if statements shows the way the compiler views the nested-if statement in DemonstrateDanglingElse.java?

    1. if (studentStatus == 1)
      if (year > 1)
          System.out.println("You're probably glad to be past your first year!");
      else
        System.out.println("Congratulations on being a graduate student!");

    2. if (studentStatus == 1)
        if (year > 1)
          System.out.println("You're probably glad to be past your first year!");
      else
        System.out.println("Congratulations on being a graduate student!");

    3. if (studentStatus == 1)
        if (year > 1)
          System.out.println("You're probably glad to be past your first year!");
        else
          System.out.println("Congratulations on being a graduate student!");

  12. Fix the dangling-else statement in DemonstrateDanglingElse.java by putting braces around the inner-if statement, like this.
  13. if (studentStatus == 1)
    {
      if (year > 1)
        System.out.println("You're probably glad to be past your first year!");
    }
    else
      System.out.println("Congratulations on being a graduate student!");

  14. Try each of the following input data values with your modified version of DemonstrateDanglingElse.java..
  15. Undergrad or grad? Year
    Test #111
    Test #212
    Test #313
    Test #414
    Test #52n/a

    Question
    10
    Which of the input values don't work correctly when you run the modified version of DemonstrateDanglingElse.java?

    1. Tests #1 and #5
    2. Test #3 and #4
    3. All tests work correctly
    4. Test #2
    5. Tests #4 and #5

E. Boolean Operators

  1. In many real-world applications, a program might need to base a decision not just on a single value, but on multiple values. As a simple example, there is no relational operator to test whether an integer is between two other values. Fortunately, Java has three Boolean operators that we can use to build up complex conditions. These operators are && (and), || (or) and ! (not).
  2. The && operator takes two Boolean expressions and returns true if both expressions are true. The || operator takes two Boolean expressions and returns true if either expression is true. The ! operator takes one Boolean expression and returns true if that expression is false, and returns false if that expression is true.
  3. Program DemonstrateBooleanOps.java below uses multiple conditions on each if statement. The program has ?? in place of the Boolean operators.
  4. DemonstrateBooleanOps.javaDownload (Help)
    // Demonstrates Boolean operators.
    
    // Replace each ?? with && or || so the program works correctly
    
    import Keyboard;
    
    public class DemonstrateBooleanOps
    {
      public static void main(String[] args)
      throws java.io.IOException
      {
        int number = Keyboard.readInt("Enter a number: ");
        
        // Check whether the user typed a number between 0 and 100
        if (number >= 0 ?? number <= 100)
        {
          System.out.println("You typed a number between 0 and 100");
        }
        else
        {
          System.out.println("You typed a number outside the range of 0 and 100");
        }
          
    
        // Check whether the user typed a number that is a multiple of
        // 2 or 3
        if (number %2 == 0 ?? number % 3 == 0)
        {
          System.out.println("You typed a number that's a multiple of 2 or 3");
        }
        else
        {
          System.out.println("You typed a number that's NOT a multiple of 2 or 3");
        }
      }
    }
    DemonstrateBooleanOps.javaDownload (Help)

  5. Download DemonstrateBooleanOps.java, and change each ?? to either && or || so the program will run correctly.
  6. Question
    11
    The correct Boolean operators in program DemonstrateBooleanOps.java are

    1. && for both if-else statements
    2. || for the first if-else statement, && for the second
    3. || for both if-else statements
    4. && for the first if-else statement, || for the second

F. Removing the ! Operator; DeMorgan's Laws

  1. It's a good idea to avoid using the ! operator as much as possible, because when a program uses many ! operators, people have a harder time understanding what the program does. If the ! operator applies to a single relational operator, then we can remove the ! operator by simply changing the relational operator to its opposite.
  2. Question
    12
    What's the opposite of the < operator?

    1. >
    2. ==
    3. <=
    4. !=
    5. >=

    Question
    13
    What's the opposite of the != operator?

    1. <=
    2. <
    3. >
    4. >=
    5. ==

    Question
    14
    Which of the following if statements is equivalent to this if statement?
    if (!(x > y)) System.out.println("yes");

    1. if (x >= y) System.out.println("yes");

    2. if (x < y) System.out.println("yes");

    3. if (x != y) System.out.println("yes");

    4. if (x == y) System.out.println("yes");

    5. if (x <= y) System.out.println("yes");

  3. If the ! operator applies to a compound Boolean expression (that is, one containing && or ||), then we can use DeMorgan's laws to distribute the ! operator over the expression. Briefly, DeMorgan's laws are
  4. !(a && b) --> !a || !b
    !(a || b) --> !a && !b

    Question
    15
    Use DeMorgan's laws to distribute the ! operator over the Boolean condition in this if statement. (Assume that variables firstBool and secondBool are Boolean variables.) Which of the following are equivalent?
    if (!(firstBool && secondBool)) ...

    1. if (firstBool || secondBool) ...

    2. if (!firstBool && !secondBool) ...

    3. if (!firstBool || !secondBool) ...

    4. if (!firstBool || secondBool) ...

    5. if (firstBool && secondBool) ...

    Question
    16
    Use DeMorgan's laws to distribute the ! operator over the Boolean condition in this if statement. (Assume that variables firstBool and secondBool are Boolean variables.) Which of the following are equivalent?
    if (!(firstBool || secondBool)) ...

    1. if (!firstBool || !secondBool) ...

    2. if (firstBool || secondBool) ...

    3. if (firstBool && secondBool) ...

    4. if (!firstBool || secondBool) ...

    5. if (!firstBool && !secondBool) ...

    Question
    17
    Use DeMorgan's laws to distribute the ! operator over the Boolean condition in this if statement. (Assume that variables x and y are int variables.) Which of the following are equivalent?
    if (!(x < 3 || y <= 2)) ...

    1. if (x > 3 && y <= 2) ...

    2. if (x < 3 && y >= 2) ...

    3. if (x >= 3 && y > 2) ...

    4. if (x <= 3 || y > 2) ...

    5. if (x < 3 || y >= 2) ...


Turn in this Assignment

First name:
Last name:
Partner's last name:

Write down your answers for your records, then press the Submit button below to turn in the lab assignment.