Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

java - Why does each element in this array of objects get overwritten by the last object?

I have the following code:

public static void main(String[] args) {
  Player players[] = new Player[2];
  Scanner kb = new Scanner(System.in);
  System.out.println("Enter Player 1's name");
  players[0] = new Player(kb.nextLine());
  System.out.println("Enter Player 2's name");
  players[1] = new Player(kb.nextLine());
  System.out.println("Welcome "+ players[0].getName() + " and " + players[1].getName());    
}

It is meant to create a new player object and store the name of the player, while keeping all the objects in the array.

Here is the player class:

public class Player {
  static String name;
  public Player(String playerName) {
    name = playerName;
  }

  public String getName(){
    return name;
  } 
}

What actually happens is that it works when I just have 1 object, but when I have 2, each element in the array is the same as the second. When I have 3 objects in the array, each element is the same as the 3rd, etc.

I'm not sure why this is happening, or how to correct it, and it's been baffling me for hours :/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Its because of the static field. Statics are used across object instances. They are stored at class level.

Below code would work:

class Player
{
    String name;

    public Player(String playerName)
    {
        name = playerName;
    }

    public String getName()
    {
        return name;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...