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.

1
2
3
4
5
// A single if/else statement
if (boolean expression)
    Do statement;
else
    Do other statement;
1
2
3
4
5
6
7
8
9
// A block if/else statement
if (boolean expression)  {
   statement1;
   statement2;
}
else {
   do other statement;
   and another one;
}

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.

coding exercise Coding Exercise

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

3-3-1: Try changing the code above to boolean isHeads = false;. What line will be printed before the after conditional?

coding exercise Coding Exercise

If/else statements can also be used with relational operators and numbers like below. Try the following code. Change age to 15 and then run it again. 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! Can you change the code to indicate that you can get a license at age 15 instead of 18? Test both possibilities. Change the boolean expression to match the laws of your state.

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 if statement in the same block of code, regardless of indentation.

1
2
3
4
5
6
// 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. How could you get the else to belong to the first if statement?

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

1
2
3
4
5
6
7
8
// Nested if with dangling else
if (boolean expression)
{
   if (boolean expression)
      do this;
}
else  // belongs to first if
  do that statement;

3.3.2. groupwork Programming Challenge : 20 Questions

Magic 8 Ball

We encourage you to work in pairs for this challenge which is on repl.it (you will need an account there if you want to save your version).

Have you ever played 20 Questions? There is great online version called Akinator that guesses a real or fictional character by asking you questions. This is a simple Artificial Intelligence algorithm that uses a decision tree of yes or no questions to pinpoint the answer. Akinator’s decision tree is very large, but we will play with a much smaller guessing game for animals.

  1. Try the program below and run it a couple times thinking of an animal and answering the questions with y or n for yes or no. Did it guess your animal? Probably not! It’s not very good. It can only guess 3 animals. Let’s try to expand it!

  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. (You may want to click on Open in Repl.it on the top right of the window and then click on Sign up or Log in to save your work). 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!

1
2
3
4
5
6
System.out.println("Is it a pet (y/n)?");
answer = scan.nextLine();
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 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!

  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.

3-3-2: After you complete your code on repl, paste in a link to it (click on share) here.

3.3.3. Summary

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

1
2
3
4
5
6
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 if statement.

You have attempted of activities on this page
Next Section - 3.4. Multi-Selection: else-if Statements