创建数组时出现Java Nullpointer异常

时间:2013-11-20 07:33:03

标签: java

我正在尝试创建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。我该怎么说这个来创建这个数组?

4 个答案:

答案 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]);
           }
    }