亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用多維數組打印星號網格?

如何使用多維數組打印星號網格?

忽然笑 2022-09-07 21:44:01
我是編程新手,我有一個練習正在殺死我。如何打印僅由星號組成的網格(5 x 6)?[稍后,這些星號將不得不替換為用StdIn.readInt()和switch語句讀取的字母,但現在我至少需要了解如何打印網格]。我將不勝感激任何幫助!更具體地說,網格應如下所示://THIS ISN'T THE CODE; JUST AN ILLUSTRATION OF WHAT SHOULD BE PRINTED  0 1 2 3 4 50 * * * * * *1 * * * * * *2 * * * * * *3 * * * * * *4 * * * * * *//I AM SUPPOSED TO START WITH SOMETHING LIKE THIS:public class Grid { static int X = 6; static int Y = 7;public static void main(String[]args) {    int [][] grid = new int [X][Y];
查看完整描述

1 回答

?
德瑪西亞99

TA貢獻1770條經驗 獲得超3個贊

這可以通過多種方式完成,但這是我這樣做的方式:


如果要打印網格,則必須使用 2 個嵌套循環。讓我們看看使用 2 個嵌套循環時會發生什么:forfor


for(int i = 0; i < 6; i++){


   for(int j = 0; j < 7; j++){


   }

}

我們從第一個循環開始:


對于 ,我們將進入第二個循環,并從 0 迭代到 6。i = 0


對于 ,我們將進入第二個循環,并從 0 迭代到 6。i = 1


...


對于 ,我們將進入第二個循環,并從 0 迭代到 6。i = 5


您應該注意的是,將迭代并取值從 0 到 6,每個值為 。ji


回到你的問題,并用我剛剛顯示的內容進行比較,你應該注意到,對于每行,你正在打印7個值(一列)。


我們假設是行數,并且是該行(列)中每個值的索引。ij


public static void printGrid() {

        for (int i = 0; i < 6; i++) {

            System.out.println();

            for (int j = 0; j < 7; j++) {

                System.out.print("*");

            }

        }

    }

此代碼打印在每行 (),7 個星號 ()。每次 i 遞增時,我們都會回到下一行 。這就是為什么我們用 把它放在循環中。ijSystem.out.println()fori


在您的情況下,我們必須稍微調整一下此代碼,以便能夠打印側面的數字以及左上角的空間。


解釋在我的代碼中的注釋中。


public class Question_55386466{


        static int X = 6;

        static int Y = 7;


        public static void printGrid() {

            System.out.print("  ");         // Printing the space on the top left corner

            for (int i = 0; i < X; i++) {

                if (i > 0) {                // Printing the numbers column on the left, taking i>0 to start from the second line (i == 1)

                    System.out.println();   // Going to the next line after printing the whole line

                    System.out.print(i - 1);//Printing the numbers of the column. Taking i-1 because we start the count for i == 1 not 0

                }

                for (int j = 0; j < Y; j++) {

                    if (i == 0)

                        System.out.print(j + "  ");//Print the first line numbers.

                    else

                        System.out.print(" * "); //if the line isn't the first line(i == 0), print the asterixes.


                }


            }

        }

您始終可以編輯 和 的值并獲得所需的結果。XY


稍后,您可以將此方法作為參數提供數組,并打印每個元素而不是星號


查看完整回答
反對 回復 2022-09-07
  • 1 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號