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 Helper Methods and Conditionals

Amit Dhamankar
Amit Dhamankar
4,163 Points

This my Example.java and PezDispenser.java

class Example {

public static void main(String[] args) {
    // Your amazing code goes here...
    System.out.println("We are making a new Pez Dispenser.");
    PezDispenser dispenser = new PezDispenser("Yoda");
    System.out.printf("The dispenser character is %s\n", dispenser.getmCharacterName());

}

}

public class PezDispenser { public static final int MAX_PEZ = 12; private String mCharacterName; private String mPezCount;

public PezDispenser(String characterName){ String mCharacterName = characterName; mPezCount = 0; } public boolean isEmpty() { return mPezCount == 0; }

public String getmCharacterName(){ return mCharacterName; }

First I compiled both the programs. Then I typed the command java-repl then I loaded the class PezDispenser.java using the command :load PezDispenser.java That was also successful But when I typed the following command: PezDispenser pd = new PezDispenser("Yoda"); and I am getting the following error: NoSuchElementException

2 Answers

Aaron Kaye
Aaron Kaye
10,948 Points

I am not too familiar with the java-repl but you do have a typo that may be messing up things. Your variable should be private int mPezCount; instead of private String mPezCount; Simple mistake! :)

This could cause a problem because in your object initializer you are setting the the variable to an int. I am surprised it compiled with that issue. Another issue is in your initializer method. You need to remove the String declaration or Java will create a new variable in that scope causing your mCharacterName to always be null in the rest of the class. See correction below:

  public PezDispenser(String characterName){ 
    mCharacterName = characterName; 
    mPezCount = 0; 
  }
Amit Dhamankar
Amit Dhamankar
4,163 Points

Aoran thanks for the answer. I figured it our just before your answer and guess what that was only the reason. Anyways I will mark it as a best answer. Thankyou.

Aaron Kaye
Aaron Kaye
10,948 Points

Thats great! Glad to have been to help! Thank you for the best answer.