Java Java Objects Meet Objects Final

Magnus Dilling Pettersen
Magnus Dilling Pettersen
5,681 Points

Why 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());
  }

}
Ruslan T
Ruslan T
1,706 Points

I'm having the same problem:

class PezDispenser{
  private String charName;

  public PezDispenser(String charName){
    this.charName = charName;

  }
  public String getCharName(){
    return charName;
  } 

  public String swapName(String charName){

    String originalName = this.charName;
    this.charName = charName;
    return originalName;

  }

}


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.getCharName());

    String before = dispenser.swapName("Darth Vader");
    System.out.printf("The dispenser is now %s, but it used to be %s %n",dispenser.getCharName(),before);
  }

}
Steven Parker
Steven Parker
203,226 Points

Ruslan 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
Ruslan T
1,706 Points

Oh oops, I actually forgot to recompile it, thanks!

1 Answer

Steven Parker
Steven Parker
203,226 Points

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