简体   繁体   中英

In Java, how would I print a 2d array that resembles a seating chart?

I have an assignment where I would have to print a 2d array (8 rows and 7 columns) that resembles a seating chart with an aisle going down the middle that cannot have any seats (these elements would be left blank). The chart would have to have a number for each seat, and continue in ascending order (as seen below).

1  2  3 x  4  5  6
7  8  9 x 10 11 12
13 14 15 x 16 17 18
19 20 21 x 22 23 24

The program would continue until there would be 48 total seats. I have to print the array with for loops (which I have no problem doing), but I do not know how to make a blank column (the column with xs), or how to make each number increase as you progress through the cells.

Right now, I have only the for loops that would print out the array.

I think what you need there is a nested loop. Your code should look like this:

 public static void main(String []args){
    print_2d_array(8, 7);
 }


 public static void print_2d_array(int rows, int columns) {
    int x = rows/2;
    int y = columns - 1;
    for(int i = 0; i < x; i++) { // number of rows
        for(int j = 0; j < y; j++) { // number of columns
            System.out.print((j + y*i + 1) + " "); // That's the formula I was talking about
            if(j == (y/2)-1) System.out.print("x ");
        }
        System.out.println();
    }
 }

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