4.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.
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
.
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.
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.
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?
4.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;
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.
4.3.2. Programming Challenge : 20 Questions¶
We encourage you to work in pairs for this challenge which is on replit.com (you will need an account there if you want to save your version).
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 below uses the following decision tree:
Try the Animal Guessing 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!
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 replit.com 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!
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.");
}
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!
How many animals can your game now guess? How many test-cases are needed to test all branches of your code?
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.
After you complete your code on replit.com, paste in your code below to run it through the auto-grader. Also include a link to your code on replit.com in comments.
Copy and paste your code from your replit.com and run to see if it passes the autograder tests. Include the link to your replit.com code in comments. Note that this code will only run with the autograder’s input and will not ask the user for input.
4.3.3. 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.
4.3.4. AP Practice¶
80
-
This would print out both “High” and “Middle”, showing that there is an error in the code. As you will see in the next lesson, one way to fix the code is to add another else in front of the second if.
60
-
This would correctly print out “Middle”.
50
-
This would correctly print out “Middle”.
30
-
This would print out “Low” which is correct according to this problem description.
-10
-
This would print out “Low” which is correct according to this problem description.
3-3-8: Consider the following code segment where a range of “High”, “Middle”, or “Low” is being determined where x is an int and a “High” is 80 and above, a “Middle” is between 50 - 79, and “Low” is below 50.
if (x >= 80)
{
System.out.println("High");
}
if (x >= 50)
{
System.out.println("Middle");
}
else
{
System.out.println("Low");
}
Which of the following initializations for x will demonstrate that the code segment will not work as intended?