我正在尝试创建一个船的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]);
}
}
每次我创建一艘新的帆船或比赛船时,我都会得到一个java.lang.NullPointerException
。我应该如何表达这个短语来创建这个数组?
Boat[] boats;
只是声明了一个Boat[]变量。您还需要用实例化它
Boat[] boats = new Boat[args.length];
"="之前的行部分表示boats是一个包含Boat实例的数组。它之后的部分实际上构造了这个空数组对象(能够包含args.length的Boat实例数),并将其分配给boats变量。
数组"boats"未初始化,这意味着它为null。
Boat[] boats
必须初始化,然后才能分配boats[i] = new RaceBoat(boatNames[i]);
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]);
}
}