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 Java Objects Harnessing the Power of Objects Incrementing and Decrementing

Cant understand this line of code , how does it keeps running after wasDispensed = true ,

public boolean dispense(){ boolean wasDispensed = false; if (!isEmpty()){ pezCount--; wasDispensed = true; }

Does the initial value of wasDispensed also changes ?

2 Answers

The true statement doesn't change the value outside of it.

public boolean dispense { //We want to dispense some candy out of the Pez dispenser
  boolean wasDispensed = false; //it's set to false because we didn't take any action yet
  if (!isEmpty) { //obviously, in order for us to dispense something, we need to be sure there is something there
   pezCount--; //if there is, we dispense
   wasDispensed = true; //it's set to true in order to check whether we dispensed something
}
}

in "wasDispensed = true" the value is set to true in order to check if we dispensed something, the code within the if statement will work until pezCount will be down to zero and there is nothing left to be dispensed. In this case, wasDispensed is not true anymore because there is no candy left to be dispensed, which will bring back the value to false.

Huzaifa Sajjad Malik
PLUS
Huzaifa Sajjad Malik
Courses Plus Student 10,823 Points
public boolean dispense()  {
 boolean wasDispensed = false; 
 if (!isEmpty())  {
 pezCount--; 
 wasDispensed = true;  
}

Okay so there is a boolean variable wasDispensed set to false and then there is a function isEmpty() which checks whether the Pezdespenser in empty or not.In the code you are calling the the invert of isEmpty() Function in the IF block which in words would be IF its not empty(i.e if the pez is not empty) the decrement PezCount by one and change the value of wasDispensed from false to true.So the code would run utntil the Pez in not completely emptied i.e until the pezCount reaches zero.