[英]How to create a 2d grid array with information from another
我正在尝试打印一个带有随机数的2d网格,以及另一个带有-1s的相等大小的网格,以代替被3整除的数字。我几乎完成了所有工作,但是第二个网格仅打印了-1s。 我究竟做错了什么? 如何获得第二个网格仅打印数字被3整除的-1s? 谢谢!
public class practice
{
public int[][] createArray(int rSize, int cSize) {
Random r = new Random();
int[][] array = new int[rSize][cSize];
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[0].length; col++) {
array[row][col] = r.nextInt(25);
}
}
return array;
}
public void print2DArray(int[][] Array) {
for (int row = 0; row < Array.length; row++) {
for (int col = 0; col < Array[0].length; col++) {
System.out.print(Array[row][col] + "\t");
}
System.out.println("\n");
}
}
public int[][] createCoords(int[][] Array) {
int[][] coord = {
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1},
{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1}
};
for (int row = 0; row < coord.length; row++) {
for (int col = 0; col < coord[0].length; col++) {
System.out.print(coord[row][col] + "\t");
}
System.out.println("\n");
}
for (int row = 0; row < coord.length; row++) {
for (int col = 0; col < Array[row].length; col++) {
if (Array[row][col] % 3 == 0) coord[row][col] = -1;
}
}
return coord;
}
public static void main(String[] args) {
Scanner in = new Scanner(System. in );
practice c = new practice();
int[][] myArray;
myArray = c.createArray(10, 10);
c.print2DArray(myArray);
c.createCoords(myArray);
}
}
看起来您在检查Array
元素是否为3的倍数之前正在打印coords
数组,而且您正在将coords
初始化为全部-1,因此将coords
的元素更改为-1不会执行任何操作。 将coords
初始化为全0(这是默认值,因此您根本不需要初始化它,只需声明它),然后在检查Array
之后将其打印出来。
一些样式方面的事情:首先,初始大写标识符通常是为类保留的,实际上,标准类库中已经有一个java.lang.reflect.Array
。 使用array
来替代,或者更好的是,使用能够描述它的使用 ,而不是它的类型的名称。 其次,您已经有了一个print2DArray
方法,为什么不在createCoords
使用它呢? 最后, coords
必须与Array
大小相同(或将其重命名为:-)),因此应这样声明。 如果更改传递给createArray
的大小,则还必须记住还要更改coords
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.