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 trial

Java

I need help understanding how a small part of this code works.

Hello, I have been working on Java objects for a few days now and understand most of the code except for the piece below. This is from the PezDispenser project and I do have it up and running. The part of code I am stuck on understanding is the following.

public boolean dispense() {

boolean wasDispensed = false;

if (!isEmpty()) {

mPezCount--;

wasDispensed = true;

}

 return wasDispensed;

}

I called up a new function named dispense. I tell the computer that a boolean value named wasDispensed is false. I than proceed as the computer determines if the pez dispenser is empty or not empty. If it is not empty, count down to 0 in the loop. It than exits the loop and the variable named wasDisopensed = true is created. if wasDispensed is now true. So in the end, what is the return wasDispensed part do? Or do I have the understanding wrong?

Thanks! Andrew

1 Answer

fadhil suhendi
fadhil suhendi
7,680 Points

Yes you are correct. If it is true, in the end It will return true, and set the function call in the Example.java to true. As you can see in the Example.java we use while loop to keep track of the dispense. In the dispense function, when the dispense is not empty than the wasDispensed will always set to true, and it will return true to the function call in the Example.java. And we know that it is a while loop, if the dispense() return true, it will keep printing out "Chomp!" until is empty and it will stop. And the number of mPezCount will decrement each time the function return true.

While you are understanding dispense function, it will make sense if you see also the Example.java, and see what does the while loop does there.

Hope this makes sense!