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 trialThierry van der Zon
291 PointsIt does not give Yoda, but it gives "null"
when i compile this i get "The dispenser is null"
and here is my code. "public 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("Chicken"); System.out.printf("The Dispenser is %s %n", dispenser.getCharacterName() ); String before = dispenser.swapHead("Darth Vader"); System.out.printf("It was %s but Chris switched it to %s %n", before, dispenser.getCharacterName()); }
}"
class PezDispenser { private String characterName;
public PezDispenser(String name) { this.characterName = characterName; }
public String getCharacterName() { return characterName; }
public String swapHead(String characterName) {
String originalCharacterName = this.characterName;
this.characterName = characterName;
return originalCharacterName;
}
}
1 Answer
Samuel Ferree
31,722 PointsYour problem is in your constructor, you are assigned the private member variable "characterName" to itself, and not the passed in variable "name" See below for the correct class implementation
class PezDispenser
{
private String characterName;
public PezDispenser(String name) {
this.characterName = name; // <---- assign the member variable, to the passed in value.
}
public String getCharacterName() {
return characterName;
}
public String swapHead(String characterName) {
String originalCharacterName = this.characterName;
this.characterName = characterName; return originalCharacterName;
}
}
Thierry van der Zon
291 PointsThierry van der Zon
291 Pointsthanks! it worked!