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 trialAndrea De Nuzzo
Courses Plus Student 639 PointsWhy in this IF WHILE loop Java doesn't get back to the "if" but keeps running the "while" code?
For what I got, if while loops run the cod as long as certain conditions are not met. So let's have a look at this code
if (!dispenser.isEmpty()){
System.out.printf("\nYour pez dispenser is full again!\n" dispenser.getCharacterName());
} while(dispenser.dispense()){
System.out.println("Chomp!");}
When i run it, Java executes only once System.out.printf("\nYour pez dispenser is full again!\n", dispenser.getCharacterName());
but once it gets to
while(dispenser.dispense()) {
System.out.println("Chomp!");
}
it runs that for 12 times (and that's ok, cause the pezs are 12).
My Question is: why doens't Java execute for 12 times the code in the "if" part too? I thought that a loop was a loop, that it was like a circle. So why doesnt it get back to the "if" part and keep stay in the while part? After all, even the condition if (!dispenser.isEmpty()) is met all the times.
Thanks!!!!!
2 Answers
andren
28,558 PointsA while
loop is indeed like a circle, but it only circles around its own body. Meaning the code found within its {} braces. Since there is only one line of code within the body:
while(dispenser.dispense()) { // This { marks the start of the loops body
System.out.println("Chomp!"); // This is the only line of code within the loop
} // This } marks the end of the loops body
Only that line gets run 12 times. If you moved the if
statement within the loop's body like this:
while(dispenser.dispense()) {
System.out.println("Chomp!");
if (!dispenser.isEmpty()) {
System.out.printf("\nYour pez dispenser is full again!\n" dispenser.getCharacterName());
}
}
Then you would have its message print multiple times too. The only time where a while
statement does not loop around its own body is when it is used in a do-while
loop, in that case it circles around the body of the do
statement instead. But that is the only exception.
Andrea De Nuzzo
Courses Plus Student 639 Pointsandren, you couldn't make the answer clearer. Great answer!!!! Thank you! :D