为什么这个对象数组中的每个元素都被最后一个对象覆盖? [英] Why does each element in this array of objects get overwritten by the last object?
问题描述
我有以下代码:
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.
这是播放器类:
public class Player {
static String name;
public Player(String playerName) {
name = playerName;
}
public String getName(){
return name;
}
}
实际发生的是,当我只有 1 个对象时它可以工作,但是当我有 2 个时,数组中的每个元素都与第二个相同.当数组中有 3 个对象时,每个元素与第 3 个相同,依此类推
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 :/
推荐答案
是因为静态字段.静态用于跨对象实例.它们存储在类级别.
Its because of the static field. Statics are used across object instances. They are stored at class level.
下面的代码可以工作:
class Player
{
String name;
public Player(String playerName)
{
name = playerName;
}
public String getName()
{
return name;
}
}
这篇关于为什么这个对象数组中的每个元素都被最后一个对象覆盖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!