简体   繁体   English

Java数组索引超出范围异常处理

[英]Java Array Index Out of Bounds Exception Processing

Given the following Java codes: 给出以下Java代码:

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: 这是因为参数只有最大索引4.然后如何更改程序以实现以下功能:一旦参数超出索引,返回值:

Math.random() * 100

If 8 is outside the range of Column 's length, that error is what you get. 如果8超出了Column的长度范围,则会出现该错误。 Change this 改变这个

int test = createIntData(Column[8]);

to (using the ternary ) 到(使用三元

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

There are 2 severe problems: 有两个严重的问题:

1.You should check, whether a given array index does exist: 1.您应该检查给定的数组索引是否存在:

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 ) 2.数组的类型( Column )与createIntData()输入参数( String )不匹配

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) 这样可以安全地使用任何输入调用该方法(尽管我在parseInt中留下了潜在的异常)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM