当我想将对象的名称设置为另一个类时,我遇到了问题,因为我一直收到 NullPointerException ,而且我不太确定如何修复此错误。
以下是一个例子:
头等舱:
//Just excuse the Vehicle class, it's just an example
private Vehicle[] car;
private int number = 1;
private int count = 0;
public store Display()
{
car = new Vehicle[number];
}
public void setVehicleName(String name)
{
car[count].setName(name);
}
public String getVehicleName()
{
return car[count].setName(name);
}
第二课:
//So, I have radio buttons, so I'll just skip to that code
if (addName.equals(e.getActionCommand()))
{
name = JOptionPane.showInputDialog(null, "Enter the vehicle name: "); //there is a private String name
name.toLowerCase(); //automatically converted to lower case
displayStore.setVehicleName(name); //assume an Display object called 'displayStore'
}
所以,如果有人有想法或知道如何解决它,我将不胜感激。谢谢!
答案 0 :(得分:2)
java中的对象数组默认设置为null,如果你这样做
Vehicle [] car = new Vehicle[number];
car[1].setName("Toyota");
您将获得NullPointerException
,因为car[1]
为空
您需要初始化数组。您可能希望在构造函数中执行此操作
public store Display()
{
car = new Vehicle[number];
for(int i=0;i<number;i++) {
car[i] = new Vehicle();
}
}
答案 1 :(得分:0)
您需要在使用前实例化car [count]。因此,请将此方法替换为:
public store Display()
{
car = new Vehicle[number];
for(int i = 0; i < count; i++)
car[i] = new Vehicle();
//Return some store type object here or change the type to void
// Moreover it is better to do initialization/instantiation in the constructor, rather
// than a separate method
}