在 Java 中,我将如何打印一个类似于座位表的 2D 数组,中间有一个'aisle'?



我正在做一项作业,我必须打印一个类似于座位表的 2D 数组。每个元素都有一个数字,当你通过数组时,数字会增加,并且在中间还有一个"过道",没有人可以坐在那里。下面是数组的外观。

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个席位为止。这将使它有 8 行和 7 列。

现在我的代码很糟糕。我试图制作用 xs 替换代码第四列的代码,但这不起作用。这是我的代码到目前为止的样子。我的代码在运行时只打印 0。我将如何使我的代码实际打印 xs,我是否可以提供一些有关如何使每个元素显示其各自编号的指示?

public class airplane {
public static void main(String[] args) {
int[] rows = new int[8];
int[] columns = new int[7];
int[][] chart = new int[rows.length][columns.length];
for(int j = 0; j < rows.length; j++)
{
for(int k = 0; k < columns.length; k++)
{
if(columns.length == 4)
{
chart[j][k] = 'x';
}
System.out.print(chart[j][k] + " ");
}
System.out.println();
}
}
}

如果我的代码不好,我深表歉意。我没有经验,我现在根本没有太多帮助。

它可以像下面一样完成 2 个 for 循环,其中第一个循环逐列迭代,第二个循环逐行迭代

public class Print2DArray {
public static void main(String[] args) {
int seatNo = 1;
int row = 8;    // set row count
int column = 7; // set column count
int[][] print2DArray = new int[row][column];  // init your 2d seat matrix
for (int i = 0; i < print2DArray.length; i++) {
for (int j = 0; j < print2DArray[i].length/2; j++) {
System.out.print(seatNo++ + " ");
//                System.out.print(print2DArray[i][j]++ + " ");  // You can use this line to print the value on the current position in the array position
}
System.out.print("x ");
for (int j = 0; j < print2DArray[i].length/2; j++) {
System.out.print(seatNo++ + " ");
//                System.out.print(print2DArray[i][j]++ + " ");  // You can use this line to print the value on the current position in the array position
}
System.out.println();
}
}
}

最新更新