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 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.