简体   繁体   English

在 Java 中,如何打印类似于座位表的二维数组?

[英]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).我有一个任务,我必须打印一个类似于座位表的二维数组(8 行和 7 列),中间有一条过道,不能有任何座位(这些元素将留空)。 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.该计划将继续进行,直到总共有 48 个席位。 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.我必须使用 for 循环打印数组(我这样做没有问题),但我不知道如何制作一个空白列(带有 xs 的列),或者如何在您通过单元格时使每个数字增加。

Right now, I have only the for loops that would print out the array.现在,我只有可以打印出数组的 for 循环。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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