Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAnas Rida
8,183 Pointsuse same if statement twice
How is it that we are able to use the "if (dispenser.isEmpty())" twice with different outcomes? In our case how did the program know which line to print???
2 Answers
Kourosh Raeen
23,733 PointsI'm not sure what you mean by different outcomes. Are you referring to the two different statements that are printed?
Kourosh Raeen
23,733 PointsYou can have as many as those if statements as you want and java goes through the in order and prints whatever string you want to print as long as the if condition is true. The first one is this:
if (dispenser.isEmpty()) {
System.out.println("The Dispenser is empty");
}
At this point in the program the dispenser is empty so dispenser.isEmpty()
return true. Since the if condition is true we see the string "The Dispenser is empty" printed on screen.
Next one is:
if (!dispenser.isEmpty()) {
System.out.println("It is no longer empty");
}
This one is coming after we've loaded the dispenser so dispenser.isEmpty()
return false but the negation operator ! turns that into true. The if condition is true so the string "It is no longer empty" gets printed.
Last one is:
if (dispenser.isEmpty()) {
System.out.println("You ate all the pez");
}
This one is coming after the while loop that keeps dispensing pez until we run out. So by the time we get to this if statement the dispenser is empty, similar to the first if statement, therefore the loop condition is true and the string "You ate all the pez" gets printed.
Hope this helps.
Anas Rida
8,183 PointsAnas Rida
8,183 Pointsyes, the two different strings that are printed