What does it mean by java.lang.ArrayIndexOutOfBoun

2020-05-06 09:31发布

问题:

my compiler keep pointing at this line:

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

and this :

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

the error is stated in the title

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);
        }
    }
}    
}

回答1:

You have declared an array of size 0, because that's what size was when the array was created. So you can't assign anything to this array. On top of that, the array's size is fixed at 0, so you can't do anything to change the size of it.

Create your array after you have assigned a number to size, so it has the proper size from the start:

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

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


回答2:

From your code:

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

Therefore, you've created an array with length 0. Since arr[0] attempts to access the first element, but a zero-length array has zero elements, you get that exception. You will have to either allocate the array with an appropriate non-zero size, or use a dynamic container such as an ArrayList.



标签: java arrays