我这里有一些代码
final Ship[] Ships = new Ship[3];
for(int x = 0; x < 3; x++)
{
Ships[x].setText("Set Ship length: " + (x+1)); // this line in particular
}
我收到一个空指针异常,我认为这是因为 Ships 对象在其包含的构造函数的参数中需要一个字符串和一个 int,您应该如何创建每个对象都需要参数的对象数组?
最佳答案
更改下面的代码..
final Ship[] Ships = new Ship[3];
for(int x = 0; x < 3; x++)
{
Ships[x].setText("Set Ship length: " + (x+1)); // this line in particular
}
到...
final Ship[] Ships = new Ship[3];
for(int x = 0; x < 3; x++)
{
String stringValue = "Set Ship length: " + (x+1); //string you want in your ship object
int intValue = 0; //int you want in your ship object..
Ship ship = new Ship(stringValue, intValue);
Ships[x] = ship;
Ships[x].setText("whatever string your heart desires"); // this line in particular
}
您正在创建一个 Ship 类型的数组,但您从未将任何内容分配给该数组。因此,当您尝试设置数组中元素的文本时,您正在尝试将文本设置为空值,这将导致空指针异常。
相反,您需要做的是首先创建一个 Ship 类型的对象,如我上面所示,然后传入您在问题。然后将此新对象添加到您的数组中。现在您可以访问数组中的对象并调用该对象的方法。
关于java - 如何创建需要参数的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23976650/