java.lang.ArrayIndexOutOfBoundsException是什么意思:0

时间:2013-08-13 00:21:39

标签: java arrays

我的编译器一直指着这一行:

arr[i] = new specialDelivery(name,name2,weight,special);

和此:

arr[i] = new specialDelivery(name,name2,weight,special);

错误在标题

中说明
public static void main ( String args [] )
{   
    int size = 0,distance;
    double weight = 0.0;
    String strinput,method,name,name2,special;
    Parcel arr[] = new Parcel[size];

    strinput = JOptionPane.showInputDialog ( " Enter number of parcel : " );
    size = Integer.parseInt(strinput);

    for (int i = 0; i<size; i++)
    {   
        int j = 0, k = 0;

        method = JOptionPane.showInputDialog ( "Method of delivery (normal/special):  " );  

        if (method.equals("normal"))
        {
            name = JOptionPane.showInputDialog ( " Enter your name : " );
            name2 = JOptionPane.showInputDialog ( " Enter name of receiver : " );
            strinput = JOptionPane.showInputDialog(" Enter the weight of parcel " + j + " : " );  
            weight = Double.parseDouble(strinput);

            strinput = JOptionPane.showInputDialog(" Enter the distance of delivery " + j + " (km) : " );  
            distance = Integer.parseInt(strinput);

            j++;
            arr[i] = new normalDelivery(name,name2,weight,distance); 
        }     

        if (method.equals("special"))
        {
           name = JOptionPane.showInputDialog ( " Enter your name : " );
           name2 = JOptionPane.showInputDialog ( " Enter name of receiver : " ); 
           special = JOptionPane.showInputDialog(" Enter the type of delivery(airplane/ship) :" );
           strinput = JOptionPane.showInputDialog(" Enter the weight of parcel " + j + " : " ); 
           weight = Double.parseDouble(strinput);

           j++;
           arr[i] = new specialDelivery(name,name2,weight,special);
        }
    }
}    
}

2 个答案:

答案 0 :(得分:9)

您声明了一个大小为0的数组,因为这是创建数组时size的内容。所以你不能为这个数组分配任何东西。最重要的是,数组的大小固定为0,因此你无法做任何事情来改变它的大小。

在为size分配号码后创建阵列,因此从一开始就具有适当的大小:

strinput = JOptionPane.showInputDialog ( " Enter number of parcel : " );
size = Integer.parseInt(strinput);

Parcel arr[] = new Parcel[size];  // move this line down here

答案 1 :(得分:0)

从你的代码:

int size = 0;
...
Parcel arr[] = new Parcel[size];

因此,您创建了一个长度为0的数组。由于arr [0]尝试访问第一个元素,但零长度数组具有零个元素,因此您会得到该异常。您必须使用适当的非零大小分配数组,或使用动态容器,例如ArrayList