簡體   English   中英

如何使用其他信息創建2D網格陣列

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM