使用二维数组和用户输入创建和填充网格

Create and fill grid using 2D array and user input

我创建了一个程序,要求用户指定网格的宽度、高度和字符。但是,当它打印网格时,它全部在一条线上,而不是二维的。

public static void main(String[] args) {

    System.out.println("A B C - create a new grid with Width A, Height B and Character C to fill grid);

    Scanner scan = new Scanner(System.in);
    int Width = scan.nextInt();
    int Height = scan.nextInt();

    char C = scan.next().charAt(0);
    char [][] grid = new char [Width][Height]; 

    for (int row = 0; row < Width-1 ; row++) {
        for (int col = 0; col < Height-1; col++) {
            grid[row][col] = C;  
            System.out.print(grid[row][col]);
        }
    }
}   

您需要在每行后打印一个新行 '\n' 字符。否则控制台将不知道一行何时完成。

此外,您没有正确命名变量。外部循环应该遍历你的行,从 0height - 1,内部(列)应该从 0width - 1。如果这令人困惑,请考虑另一种常用的像素索引方式:xy。而 x 表示您在哪一列,为什么 y 表示您在哪一行。

int width = scan.nextInt();
int height = scan.nextInt();

char c = scan.next().charAt(0);
char [][] grid = new char [width][height]; 

for (int row = 0; row < height - 1; col++) {    
    for (int col = 0; col < width - 1; row++) {
        grid[col][row] = c;  
        System.out.print(grid[col][row]);
    }
    System.out.print("\n");
}

此外请注意,我擅自用小写字母(heightwidth)命名了您的变量,以使它们符合 java naming conventions.