Time estimate: 90 min.

3.3. Two-way Selection: if-else Statements

What if you want to pick between two possibilities? If you are trying to decide between a couple of things to do, you might flip a coin and do one thing if it lands as heads and another if it is tails. In programming, you can use the if keyword followed by a statement or block of statements and then the else keyword also followed by a statement or block of statements.

// A block if/else statement
if (boolean expression)
{
   statement1;
   statement2;
}
else
{
   do other statement;
   and another one;
}
// A single if/else statement
if (boolean expression)
    Do statement;
else
    Do other statement;

The following flowchart demonstrates that if the condition (the boolean expression) is true, one block of statements is executed, but if the condition is false, a different block of statements inside the else clause is executed.

../_images/Condition-two.png

Figure 1: The order that statements execute in a conditional with 2 options: if and else

Note

The else will only execute if the condition is false.

Try the following code. If isHeads is true it will print Let's go to the game and then after conditional.

exercise Check your understanding

If/else statements can also be used with relational operators and numbers like below. If your code has an if/else statement, you need to test it with 2 test-cases to make sure that both parts of the code work.

coding exercise Coding Exercise

Run the following code to see what it prints out when the variable age is set to the value 16. Change the variable age’s value to 15 and then run it again to see the result of the print statement in the else part. Can you change the if-statement to indicate that you can get a license at age 15 instead of 16? Use 2 test cases for the value of age to test your code to see the results of both print statements.

The following program should print out “x is even” if the remainder of x divided by 2 is 0 and “x is odd” otherwise, but the code is mixed up. Drag the blocks from the left and place them in the correct order on the right. Click on Check Me to see if you are right.

coding exercise Coding Exercise

Try the following code. Add an else statement to the if statement that prints out “Good job!” if the score is greater than 9. Change the value of score to test it. Can you change the boolean test to only print out “Good job” if the score is greater than 20?

3.3.1. Nested Ifs and Dangling Else

If statements can be nested inside other if statements. Sometimes with nested ifs we find a dangling else that could potentially belong to either if statement. The rule is that the else clause will always be a part of the closest unmatched if statement in the same block of code, regardless of indentation.

// Nested if with dangling else
if (boolean expression)
   if (boolean expression)
      Do statement;
   else  // belongs to closest if
      Do other statement;

coding exercise Coding Exercise

Try the following code with a dangling else. Notice that the indentation does not matter to the compiler (but you should make it your habit to use good indentation just as a best practice). How could you get the else to belong to the first if statement?

You can use curly braces ({}) to enclose a nested if and have the else clause belong to the the top level if clause like below:

// Nested if with dangling else
if (boolean expression)
{
   if (boolean expression)
      Do this statement;
}
else  // belongs to first if
  Do that statement;

In fact many experienced Java programmers always use curly braces, even when they are not technically required to avoid this kind of confusion.

3.3.2. Math.random() in if Statements

The Math.random() method returns a random number between 0.0 and 1.0. You can use this method with if statements to simulate a coin flip or an event occuring a certain percentage of the time. For example, if you want to simulate a coin flip, you can check if the random number is less than 0.5 (halfway between 0 and 1) to simulate a 50% chance of heads or tails:

if (Math.random() < 0.5)
{
    System.out.println("Heads");
}
else
{
    System.out.println("Tails");
}

If you want to simulate an event occuring 90% of the time, you can check the random number to see if it is less than 0.9 (90% of the way between 0 and 1):

if (Math.random() < 0.9)
{
    // 90% of the time
    System.out.println("Event happened");
}
else
{
    // 10% of the time
    System.out.println("Event did not happen");
}

exercise Check your understanding

coding exercise Coding Exercise

Add an if/else statement that uses Math.random() to do a coin flip to decide whether to call yertle.turnRight() or yertle.turnLeft. Run the code to see the turtle draw a random shape.

3.3.3. groupwork Programming Challenge : 20 Questions

../_images/questionmark.jpg

Have you ever played 20 Questions? 20 Questions is a game where one person thinks of an object and the other players ask up to 20 questions to guess what it is.

There is great online version called Akinator that guesses whether you are thinking of a real or fictional character by asking you questions. Akinator is a simple Artificial Intelligence algorithm that uses a decision tree of yes or no questions to pinpoint the answer. Although Akinator needs a very large decision tree, we can create a guessing game for animals using a much smaller number of if-statements.

The Animal Guessing program that we will make uses the following decision tree:

../_images/decision-tree.png

Figure 2: Animal Guessing Game Decision Tree

  1. Try the Animal Guessing game below. In Runestone, you need to provide the input below the code before you run it. It is set to answer the questions with y and y. Run the code to see the result. Change the input below the coding window to y n and n to guess the other animals. It can only guess 3 animals. Let’s add more! To see this program in an interactive input IDE, try it in JuiceMind or replit or your local IDE (where you should change the lines with scan.next() to scan.nextLine()).

  2. In the very last else clause, the program knows that it is not a mammal and it guesses a bird. Let’s add to that part. Instead of saying “I guess a bird! Click on run to play again.”, change it to ask a question that distinguishes between birds and reptiles (for example does it fly?). Then, get their response and use an if statement to guess “bird” or “turtle” (or another reptile). For example, here’s how we decided to choose between a dog or an elephant. We asked the question “Is it a pet?”, got the response, and then with an if statement on the y/n answer we determined dog or elephant. You would use similar code to distinguish between a bird and a turtle. Run your code and test both possibilities!

System.out.println("Is it a pet (y/n)?");
answer = scan.next(); // or nextLine() in your own IDE
if (answer.equals("y"))
{
    System.out.println("I guess a dog! Click on run to play again.");
}
else
{
    System.out.println("I guess an elephant! Click on run to play again.");
}
  1. Did you notice that when it asked “Is it a pet?” and you said “y”, it immediately guessed “dog”? What if you were thinking of a cat? Try to come up with a question that distinguishes dogs from cats and put in code in the correct place (in place of the code that prints out “I guess a dog”) to ask the question, get the answer, and use an if/else to guess cat or dog. Run your code and test both possibilities by adding more input.

  2. How many animals can your game now guess? How many test-cases are needed to test all branches of your code?

  3. If your class has time, your teacher may ask you to expand this game or to create a similar game to guess something else like singers or athletes. Spend some time planning your questions on paper and drawing out the decision tree before coding it.

The code below is a simple 20 questions game that guesses an animal. In Runestone, you need to provide the input below the code before you run it. It is set to answer the questions with y and y. Run the code to see the result. Change the input to guess the other animals. It can only guess 3 animals. Let’s add more! Add a question and if/else statement on line 20 to distinguish a cat and a dog and on line 31 to distinguish a turtle and a bird. Change the input below the code to test your new questions and answers.

3.3.4. Summary

  • If statements can be followed by an associated else part to form a 2-way branch:

if (boolean expression)
{
    Do statement;
}
else
{
    Do other statement;
}
  • A two way selection (if/else) is written when there are two sets of statements: one to be executed when the Boolean condition is true, and another set for when the Boolean condition is false.

  • The body of the “if” statement is executed when the Boolean condition is true, and the body of the “else” is executed when the Boolean condition is false.

  • Use 2 test-cases to find errors or validate results to try both branches of an if/else statement.

  • The else statement attaches to the closest unmatched if statement in the same block of statements.

3.3.5. AP Practice

You have attempted of activities on this page