我有一个作业,必须打印一个二维数组(8 行和 7 列),该数组类似于座位表,中间有一条过道,不能有任何座位(这些元素将留空)。图表中的每个席位必须有一个编号,并按升序排列(如下所示)。
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
该计划将继续进行,直至席位总数达到 48 个为止。 我必须使用 for 循环打印数组(我这样做没有问题),但我不知道如何创建空白列(带有 xs 的列),或者如何在单元格中前进时使每个数字增加。
现在,我只有 for 循环可以打印出数组。
最佳答案
我认为你需要的是一个嵌套循环。您的代码应如下所示:
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();
}
}
关于java - 在 Java 中,如何打印类似于座位表的二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61845027/