0

我有这个简单的代码:

double[][] params = new double[][]{{197.0,258.0,427.0,426.0,507.0,524.0,386.0},
    {345.0,473.0,484.0,422.0,406.0,291.0,289.0}};       

for (int i = 0; i <= params.length; i++) {
    for (int j = 0; j <= params[i].length; j++) {
        System.out.println("Coordinates: " + params[i][j]); //line 29       
    }
}

和错误:

> Caused by: java.lang.ArrayIndexOutOfBoundsException: 7    at
> com.eyecom.gen.generate_xml(gen.java:29)  

为什么我会得到这个异常?

4

3 回答 3

5

在 Java 中,数组是从零开始的。在这里,您超出了数组范围。采用

for (int i = 0; i < params.length; i++) {
    for (int j = 0; j < params[i].length; j++) {
于 2013-03-29T18:28:52.750 回答
3

尝试

for (int i = 0; i < params.length; i++) {
    for (int j = 0; j < params[i].length; j++) {
        System.out.println("Coordinates: " + params[i][j]); // line 29
    }
}

数组中的索引是 from 0tolength-1所以你不想使用索引等于length.

于 2013-03-29T18:29:00.867 回答
2

更改 for 循环结构

 for (int i = 0; i <= params.length; i++) {
    for (int j = 0; j <= params[i].length; j++) {
        System.out.println("Coordinates: " + params[i][j]); //line 29               
    }
}

for (int i = 0; i < params.length; i++) {
    for (int j = 0; j < params[i].length; j++) {
        System.out.println("Coordinates: " + params[i][j]); //line 29               
    }
}
于 2013-03-29T18:29:42.623 回答