2.1.7 How to Write a Nested If Statement

Nested if statements are used when you need two different things to happen based on separate conditions. Many times nested if statements are used as a kind of "chain logic" to aid in decision making.

Let's look at the Employee's Eat method.

Currently if the food object's Weight is within range the Employee will always gain Weight, the food will always be eaten, the food will always receive a rating and the Employee will always Burp.


But here at the ComoZoo, Employees only Burp after eating food if it's decently good. That's just how they show they like things don't think about it. So really, we only want the Employees to Burp if a given condition is met. To do this we will add a nested if statement inside the existing if statement.

So if we run the application and step through the code we can see that the Rating of the Cheetah Chips is 4 so the conditional evaluates to true and the Employee burps.

But if the Employee eats a food item with a poor rating...

...and we step through the code, the Employee will never lose weight because Burp is never called due to the conditional evaluating false..