更改条件(多维数组)时,为什么我的for循环不起作用? [英] Why does my for loop not work when i change the condition(multidimensional arrays)?

查看:64
本文介绍了更改条件(多维数组)时,为什么我的for循环不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名新程序员,正在学习多维数组。我写了这个简单的代码,不知道为什么会出现此编译错误:

I'm a new programmer and I'm learning multidimensional arrays. I wrote this simple code and I dont know why I get this compile error:

线程 main中的异常java.lang.ArrayIndexOutOfBoundsException:2
在Arrays .main(Arrays.java:21)

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at Arrays.main(Arrays.java:21)

 public class Arrays {

    public static void main(String[] args) {

        int [][][] a  = new int [2][3][4];

        for(int i = 0; i < a.length; i++){

            for(int j = 0; j < a[i].length; j++){

                for(int k = 0; k < a[j].length; k++){
                System.out.print(a[i][j][k]);
            }
            System.out.println();
        }
        System.out.println();
    }
    System.out.println();
 }
}

如果我将数组更改为3x3x3,则代码有效

If I change the array to be 3x3x3 the code works

public class Arrays {

    public static void main(String[] args) {

        int [][][] a  = new int [3][3][3];

        for(int i = 0; i < a.length; i++){

            for(int j = 0; j < a[i].length; j++){

                for(int k = 0; k < a[j].length; k++){
                System.out.print(a[i][j][k]);
            }
            System.out.println();
        }
        System.out.println();
    }
    System.out.println();
 }
}

为什么?

推荐答案

非常简单。您的数组没有相同的行和列来处理这样的迭代。您可以清除自己的疑问。只需打印出i,j和k的值。您将能够看到,在迭代的某个时刻,没有这样的索引可以引用。因此,这是一个编译时错误

Its very simple . Your array does not have equal rows and columns to process such an iteration . You can clear your own doubt . Just print out values of i , j , and k . You will be able to see that at certain point in your iteration there is no such index to be referred . Hence it is a compile time error

这篇关于更改条件(多维数组)时,为什么我的for循环不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆