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 (Retired) Harnessing the Power of Objects Method Signatures

Adam Brown
Adam Brown
1,893 Points

Why does while (dispenser.dispense()) { System.out.println("Chomp!"); } actually cause the dispenser to dispense?

My understanding of while() is that it is stating while "this" is true, this will happen. I don't understand how this line of code actually will make pez dispense. I would understand if it were something like while(mPezCount>0){dispenser.dispense();}, but just don't see how putting something in the while parentheses calls for an action to take place. Does it have something to do with it being a boolean statement?

1 Answer

Christopher Augg
Christopher Augg
21,223 Points

Adam,

Yes, it does have to do with it being a boolean statement. The dispense() method can be called like this as long as it returns a boolean.

The dispense method returns a boolean.

       public static boolean despense() {

        //initializes to false
         boolean wasDispensed = false; 

        //calls isEmpty() to make sure it is not empty using !
        if(!isEmpty()) {
            // Only decrements if mPezCount is not empty
            mPezCount--;        
            // Only assigns true if mPezCount is not empty. 
            wasDispensed = true; 
        }
        // Returns false if mPezCount is empty. Returns true if mPezCount is not empty.
        return wasDispensed;
    }

         // On each iteration- if dispense() returns true (not empty), execute inner block.
         //                    if dispense() returns false(is empty), break out of while loop. 
         while (dispenser.dispense()) { 
               System.out.println("Chomp!"); 
         }

Basically, the while statement reads : I will continuously call the dispense() method and execute the code within its block as long as the Pez dispenser is not empty.

I hope this helps.

Regards,

Chris