2015-11-16 31 views
2

我试图用随机数打印一个二维网格,使用-1s代替另一个同样大小的网格来代替可以被3整除的数字。我完成了很多一切,但第二个网格只打印-1s。我究竟做错了什么?我怎么能得到第二个网格只打印-1s的数字可以被3整除?谢谢!如何使用另一个信息创建二维网格数组

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

    } 

} 

回答

0

它看起来像你打印coords数组你检查Array元素是3的倍数之前,再加上你初始化coords所有-1因此改变coords元素为-1什么也没做。将coords初始化为全0(这是默认值,因此您不需要初始化它,只需声明它),然后在检查Array后打印它。

一些风格的东西:首先,初始的大写标识符通常是为类保留的,事实上标准类库中已经有一个java.lang.reflect.Array。改为使用array,或更好地使用描述它的名称使用,而不是它的类型。其次,您已经有了print2DArray方法,为什么不在createCoords中使用它?最后,coords需要与Array(或任何您将其重命名为:-))的大小相同,因此您应该声明它。如果您将更改的尺寸更改为createArray,则必须记住更改coords