Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Java Objects Meet Objects Final

Charlie Flowers
Charlie Flowers
612 Points

Why does this code not work?

For the Pez project I am using this code, but it does not work what should I do?

The PezDispenser.java code is

class PezDispenser {

private String mCharacterName;

public PezDispenser(String characterName) { mCharacterName = characterName;

}

public String getCharacterName() { return mCharacterName; }

public String swapHead(String characterName) { String origanalCharacterName = this.characterName; this.characterName = characterName; return origanalCharacterName; }

}

And the Example.java code is

public class Example {

public static void main(String[] args) { System.out.println("\nWe are making a new PEZ dispenser\n"); PezDispenser dispenser = new PezDispenser("Yoda");

System.out.printf("The dispenser is %s %n",
                  dispenser.getCharacterName()
                 );
String before = dispenser.swapHead("Darth Maul");
System.out.printf("It was %s but Yoda switched it to %s %n",
                  before,
                  dispenser.getCharacterName());

}

}

Why does this not work? And what should I change?

gurveer aulakh
gurveer aulakh
2,800 Points

what error does the compiler give to the program?

In the public String swapHead method, you call this.characterName, but there is no variable with that name, as you declared it as mCharacterName in the first line of the body of you PezDispenser class. You could either use this.mCharacterName or just mCharacterName.