我正在尝试创建array
个小船,其中包含RaceBoat
个对象和SailBoat
个对象。目前我有这个:
Boat[] boats;
totalBoatCount = args.length;
for (int i = 0 ; i < totalBoatCount ; i++)
{
char firstChar = boatNames[i].charAt(0);
if (Boat.isItRaceBoat(firstChar))
{
boats[i] = new RaceBoat(boatNames[i]);
}
else
{
boats[i] = new SailBoat(boatNames[i]);
}
}
每次创建新的SailBoat或RaceBoat时,我都会得到java.lang.NullPointerException
。我该怎么说这个来创建这个数组?
答案 0 :(得分:4)
Boat[] boats;
只声明一个Boat []变量。您还需要使用
实例化它Boat[] boats = new Boat[args.length];
'='之前的行部分表示boat是包含Boat实例的数组。它之后的部分实际构造了这个空数组对象(能够包含args.length数量的Boat实例)并将它分配给船只变量。
答案 1 :(得分:2)
数组“boats”未初始化,这意味着它为null。
答案 2 :(得分:1)
Boat[] boats
之前,必须先初始化 boats[i] = new RaceBoat(boatNames[i]);
答案 3 :(得分:0)
Boat[] boats
Boat[] boats = new Boats[args.length];
for (int i = 0 ; i < boats.length ; i++)
{
char firstChar = boatNames[i].charAt(0);
if (Boat.isItRaceBoat(firstChar))
{
boats[i] = new RaceBoat(boatNames[i]);
}
else
{
boats[i] = new SailBoat(boatNames[i]);
}
}