Java for循环没有正确填充数组

nic*_*ndo 1 java combinations loops permutation multidimensional-array

我有以下代码:

public class solutionsTest {
    public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
        int allsolutions[][][][][] = new int[16][16][16][16][16];

        for (int i = 0; i <= 15; i++) {
            for (int j = 0; j <= 15; j++) {
                for (int k = 0; k <= 15; k++) {
                    for (int l = 0; l <= 15; l++) {
                        allsolutions[i][j][k][l][j] = i;
                        System.out.println("Set index " + i + " " + j + " " + k + " " + l + " " + j + " equal to " + i);
                    }
                }
            }
        }

        System.out.println(allsolutions[4][2][1][4][5]);
        System.out.println(allsolutions[5][2][1][4][5]);
        System.out.println(allsolutions[6][2][1][4][5]);
        System.out.println(allsolutions[7][2][1][4][5]);
        System.out.println(allsolutions[8][2][1][4][5]);
    }
}
Run Code Online (Sandbox Code Playgroud)

循环内的println检查正确地正确报告存储的数据,因为您可以看到是否运行该程序.但是,在循环之后,如果我尝试检索循环内设置的任何值,则所有值都为0.我缺少什么?

在循环中设置,所有值都应该对应于数组的第一个维度的索引:

allsolutions [0] [x] [x] [x] [x] = 0;

allsolutions [1] [x] [x] [x] [x] = 1;

allsolutions [2] [x] [x] [x] [x] = 2;

等等...

Era*_*ran 9

您永远不会将任何内容分配给allsolutions[4][2][1][4][5]您正在打印的任何其他4个阵列位置,因此它们保持为0.您的阵列中只有4个嵌套循环和5个维度.

您只能将值分配给第二个索引等于第五个索引的位置.例如,如果您尝试打印,System.out.println(allsolutions[4][2][1][4][2]);则会看到非零值.

你应该使用5个嵌套循环而不是重用j索引:

for(int i=0;i<=15;i++){
    for(int j=0;j<=15;j++){
        for(int k=0;k<=15;k++){
            for(int l=0;l<=15;l++){
              for(int m=0;m<=15;m++){
                allsolutions[i][j][k][l][m] = i;
                System.out.println("Set index "+ i + " " + j + " " + k + " " + l + " " + m + " equal to " + i);
              }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)