我正在尝试打印一个带有随机数的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);
}
}
coords
在检查Array
元素是否为3的倍数之前,您似乎正在打印数组,另外还要初始化coords
为全部-1,因此将元素更改coords
为-1不会执行任何操作。初始化coords
为全0(这是默认值,因此您根本不需要初始化它,只需声明它),然后在选中后打印出来Array
。
一些样式方面的事情:首先,初始大写标识符通常是为类保留的,实际上java.lang.reflect.Array
,标准类库中已经有一个。改用array
或更好的方法是使用描述它的用法的名称,而不是其类型。其次,您已经有了一种print2DArray
方法,为什么不使用它createCoords
呢?最后,coords
大小必须与Array
(或将其重命名为:-)的大小)相同,因此应这样声明。如果您更改传递给的大小createArray
,则还必须记住也要进行更改coords
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句