1 回答

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
稍后,您可以將此方法作為參數提供數組,并打印每個元素而不是星號
添加回答
舉報