gpt4 book ai didi

java - 如何将一个对象放入数组中

转载 作者:行者123 更新时间:2023-12-01 18:07:51 25 4
gpt4 key购买 nike

如何将对象放入数组中?这是我的数组。

public static Player [] playerArray;
Player[] playerArray = new Player [2];

玩家

public class Player {
private String wpm;
private String mistakes;
private String time;

public Player (String nwpm,String nmistakes, String ntime){
wpm = nwpm;
mistakes = nmistakes;
time = ntime;
}

public String getWPM(){
return wpm;
}
public String getMistakes(){
return mistakes;
}
public String getTime(){
return time;
}
}

我一直收到此错误

Exception in thread "main" java.lang.NullPointerException

每当我尝试使用播放器时。我做错什么了吗?您还需要什么吗?

编辑:添加错误发生的位置

public void setPlayer1(Player p){
p1WPM.setText("8");
p1Mis.setText(p.getMistakes());
p1Time.setText(p.getTime());
}

最佳答案

例如,要在数组中添加 Player 对象,您可以执行以下操作:

Player[] playerArray = new Player [2];

//Create new Player object using the defined constructor
p = new Player("a","b","c");

// Assign p to 1st index of array
playerArray[0] = p;

关于java - 如何将一个对象放入数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34916308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com