简体   繁体   中英

Create and fill grid using 2D array and user input

I created a program which asks the User to specify the width, height and characters for a grid. However, when it prints the grid, it is all on one line and not 2D.

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

You need to print a new line '\\n' character after each line. Otherwise the console will not know when a row has finished.

Also you didn't name your variables correctly. The outer loop should iterate over your rows and go from 0 to height - 1 and the inner (columns) should go from 0 to width - 1 . If this is confusing, think of another common way of indexing pixels: x and y . while x denotes in which column you are, why y denotes in which row you are.

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

In addition please note that I took the liberty and named your variables with lower letters ( height and width ) to bring them in line with the java naming conventions .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM