Week 2 Meeting 2

Nested if statements

When one of the branches of an if statement contains another if statement, we call the whole statement a nested if statement, because one if is nested inside another.

 

At this point in our tenure, we have always had an else branch for each if, so the keywords if and else must be matched, similar to the way { } and ( ) must be matched.

 

Use a nested if when one branch of the problem contains multiple possible outcomes.

 

Example: Categorize a number entered by the user

if it is negative, print a message that it was a negative number

otherwise, if it is between 0 and 100, inclusive, print it and note that the input was 0 - 100.

otherwise, if it is greater than 100, bring it into the range 0 – 99 and then if it is greater than 50, print “modulated number “ <the modulated number> “ is between 50 and 100”.

 

A new operator, modulo (%).  Means ‘the remainder’ of an integer division.

Integer division is 4th grade division:

Consider 2 / 5:

(5 goes into 2 zero times with remainder two)

 

So both of the following are true,

2 / 5 == 0

2 % 5 == 2

 

Develop some tests to ensure you understand the problem.

 

See ../demos/W02N02.java

 

Use a nested if to choose among several like alternatives.

 

Exercise: “WeatherChooser”

Ask the user to choose their favorite weather from: 1. sun, 2. rain, 3. snow, 4. sleet, 5. hail.

After they give you a number, print the description of the weather they like best, so if they choose 4, you must print the String sleet.

If statement heuristic (rule of thumb):

 

Structure all if statements, so they nest on the else branch.  NOT on the then branch, i.e., the keyword else should not appear inside any then branch.

This strategy makes the if statement much easier to comprehend.

 

If all nested if statements are on the else branch, we usually collapse the indentation to make the if-statement easier to read.  See ../demos/WeatherChooser.java for my solution to the exercise shown above.