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

标签 java loops multidimensional-array combinations permutation

我有以下代码:

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]);
    }
}

循环内部的 println 检查正确地报告了存储的数据,如果你运行程序就可以看到。但是,在循环之后,如果我尝试检索在循环内设置的任何值,所有值 = 0。我错过了什么?

如在循环中设置的那样,所有值都应对应于数组第一维的索引:

所有解决方案[0][x][x][x][x] = 0;

所有解决方案[1][x][x][x][x] = 1;

所有解决方案[2][x][x][x][x] = 2;

等等……

最佳答案

您永远不会为 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);
              }
            }
        }
    }
}

关于Java for 循环没有正确填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31234092/

相关文章:

java - Struts 应用中的 EJB 和 Hibernate

javascript - 在 javascript 中正确使用 continue

javascript - 鼠标移动时的空闲事件 - 如何创建循环?

java - 对数组中的字符串和 double 类型进行排序

Javascript 无限嵌套数组处理

java - 按二维对二维数组进行排序

java - 在 Java 中逐行读取文本文件的最快方法

java - 防止 Java Applet 类加载器尝试远程检索类

java - Spring boot 应用程序在基于角色的登录后显示 "White level Error"

loops - 如何在PowerShell中使用while循环将ppm数据从blender frameserver传输到ffmpeg