public class Jeux {
public static void main(String [] args) {
int nPlayer= 0;
String name;
boolean ok = false;
Player[] groupe = null;
do {
try {
System.out.print("How many player: ");
nPlayer= Clavier.lireInt();
ok = true;
} catch(NumberFormatException e) {
System.out.println("ERROR, enter a number");
}
} while(!ok);
groupe = new Player[nPlayer];
System.out.println(groupe.length);
for(int i=0; i<groupe.length; i++){
try{
System.out.print("Enter the name of the player " + (i + 1));
name = Clavier.lireString();
groupe[i].setNom(name);
} catch(NullPointerException e) {
System.out.println(e.getMessage());
}
}
}
}
为什么我无法设置 groupe[i]
--> groupe[i].setNom(nom);
的名称。我遇到了一个异常(exception)。
我尝试在不知道数组长度的情况下创建多个对象。
也许数组列表和其他方法还有其他可能性,但我在学校,暂时没有看到其他方法。
最佳答案
除了实例化保存它们的数组之外,您还需要实例化每个 Player
对象:
name = Clavier.lireString();
groupe[i] = new Player(); // replace this with actual constructor
groupe[i].setNom(name);
您的代码正在捕获 NullPointerException
这正是我对您当前代码的期望。
关于java - 将值设置为对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33949047/