Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将一维数组渲染为网格?_Java - Fatal编程技术网

Java 将一维数组渲染为网格?

Java 将一维数组渲染为网格?,java,Java,我可以在网格中绘制二维数组,如下所示: int[][] foo = new int[10][10]; // assume the array is full of data for (int x = 0; x < 10; x++) { for (int y = 0; y < 10; y++) { g.setColor(new Color(foo[x][y] & 255, foo[x][y] & 255, foo[x][y] & 255

我可以在网格中绘制二维数组,如下所示:

int[][] foo = new int[10][10];

// assume the array is full of data
for (int x = 0; x < 10; x++) {
    for (int y = 0; y < 10; y++) {
        g.setColor(new Color(foo[x][y] & 255, foo[x][y] & 255, foo[x][y] & 255));
        g.fillRect(x * 50, y * 50, 50, 50);
    }
}
int[]foo=newint[10][10];
//假设数组中充满了数据
对于(int x=0;x<10;x++){
对于(int y=0;y<10;y++){
g、 setColor(新颜色(foo[x][y]&255,foo[x][y]&255,foo[x][y]&255);
g、 fillRect(x*50,y*50,50,50);
}
}
有什么办法可以让我也这么做吗 一维数组?有什么神奇的吗 数学运算我可以做每一次迭代, 还是必须将其填充到二维数组中
手动?

当然可以。考虑一个按顺序分配值的网格,如下所示:

[ 0] [ 1] [ 2] [ 3]
[ 4] [ 5] [ 6] [ 7]
[ 8] [ 9] [10] [11]
[12] [13] [14] [15]
每行从4r开始,该行中的每列只添加一个偏移量。因此,index=4r+c,其中r和c都是基于0的。系数4来自每行的宽度;由于每行有4个元素,因此每行的开头比上一行的开头大4个

用Java术语来说,您将有:

int index = width * y + x;
int f = foo[index];
例如,上面的单元格
[14]
位于x=2,y=3(请记住,这些值是0索引的)。插入宽度=4,我们得到:

index = width * y + x
      =   4   * 3 + 2
      =   14

如果要在每行X个元素的网格中打印一个一维数组,可以执行以下操作

int[][] foo = new int[20];

for (int x = 0; x < 20; x++) {
    if(x % 5 == 0 && x != 0) //so when x is 5, 10, 15, 20
        //go in a new line
}

您可以使用余数和除法。如果增加索引,余数将每次增加1,直到宽度为1,然后再次为0。如果索引/宽度达到下一个完整的除法,则您的除法值将增加1

int width=10;
for (int index = 0; index < 100; index++) {
        g.setColor(Color.RED);
        g.fillRect((index%width) * 50, (index/width) * 50, 50, 50);
}
int-width=10;
对于(int-index=0;index<100;index++){
g、 setColor(Color.RED);
g、 fillRect((指数百分比宽度)*50,(指数/宽度)*50,50,50);
}

另外,看起来您甚至没有使用阵列…使用1D?10x10条目数等于100条目数的阵列网格的预期结果是什么。因此,使用100个条目的1D数组…使用%的模运算符(它给出除法的剩余部分)和/除法operator@m_callens我这样做是因为我想获取一个一维数组(java从listFiles()提供给您的目录中有多少文件的列表),并将它们显示为网格状。幸运的是,希望能有所帮助的东西起了作用,所以我只是在等待,直到我能接受他的答案。我在头脑中的问题中加入了一个例子,所以有一些错误,但我不想粘贴项目中的代码文件。
int width=10;
for (int index = 0; index < 100; index++) {
        g.setColor(Color.RED);
        g.fillRect((index%width) * 50, (index/width) * 50, 50, 50);
}