chrisTina
chrisTina

Reputation: 2378

Java Array Index Out of Bounds Exception Processing

Given the following Java codes:

int test = createIntData(Column[8]);

private int createIntData (String realData) {
    if (realData == null) {
        return (int) (Math.random()*100); 
    }
    else {
        return Integer.parseInt(realData);
    }
}

This throws exception like this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

This is because the argument only have an maximum index of 4. Then how to change the program to realize the function that: once the argument is out of index, return the value:

Math.random() * 100

Upvotes: 1

Views: 1530

Answers (3)

njzk2
njzk2

Reputation: 39403

I would go with allowing for check inside the method, by passing array and index:

public int createIntData(String[] values, int index) {
    if (values != null && index >= 0 && index < values.length) {
        return Integer.parseInt(values[index]);
    }
    return (int) (Math.random()*100);
}

Call it:

int test = createIntData(Column, 8);

This way the method can safely be called with any input (I left the potential exception in the parseInt, though)

Upvotes: 1

SME_Dev
SME_Dev

Reputation: 1890

There are 2 severe problems:

1.You should check, whether a given array index does exist:

Column[] array = new Column[someCapacity];
//fill the array

int i = 8;

if( i < array.length && i > -1 ){
    int test = createIntData(array[i]);
}

2.The array's type(Column) does not match the createIntData() input parameter (String)

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201537

If 8 is outside the range of Column's length, that error is what you get. Change this

int test = createIntData(Column[8]);

to (using the ternary)

int test = createIntData((8 < Column.length) ? Column[8] : null);

Upvotes: 1

Related Questions