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 trialMagnus Dilling Pettersen
5,681 PointsWhy does Yoda appear, and not Darth Vader?
class PezDispenser {
private String characterName;
public PezDispenser(String characterName) {
this.characterName = characterName;
}
public String getCharacterName() {
return characterName;
}
public String swapHead(String CharacterName) {
String originalCharacterName = this.characterName;
this.characterName = characterName;
return originalCharacterName;
}
}
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("Yoda");
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());
}
}
Steven Parker
231,275 PointsRuslan T — I don't see your issue. Running your code produces this:
We are making a new Pez dispenser
The dispenser is Yoda
The dispenser is now Darth Vader, but it used to be Yoda
Did you perhaps forget to save your changes or recompile?
Ruslan T
1,706 PointsOh oops, I actually forgot to recompile it, thanks!
1 Answer
Steven Parker
231,275 PointsYou have "CharacterName" (capital "C") as the parameter instead of "characterName" (lower-case "c"):
public String swapHead(String CharacterName) {
This causes the method to just assign the current name back to itself instead of the new one.
Personally, I use completely different names for parameters than any private fields to prevent these kinds of things from passing unnoticed by the compiler.
Ruslan T
1,706 PointsRuslan T
1,706 PointsI'm having the same problem: