座位预订
Seats Reservation
我正在尝试使用二维数组进行座位预订。我遇到了一个问题,输出似乎不正确,我不知道如何处理它。我已经尝试了很多次,但仍然没有做对。我只想将星号放在 2d table 或行和列内。星号代表座位。
public class BusSeatReservation {
public static void main(String args[]) {
System.out.println("\t\t\t\tBUS SEAT RESERVATION");
char [][] matrix = new char [11][10];
for (int col = 1; col <= 4; col++) {
System.out.print("\t\tCol " + (col) + "\t");
}
System.out.println();
for (int row = 1; row <= 10; row++) {
System.out.println("Row " + (row) + "\t|");
for (int seat = 1; seat <= 4; seat++) {
matrix [row] [seat] = '*';
System.out.print(matrix [row] [seat] + "\t\t");
}
}
System.out.println();
}
}
问题是您在循环内的错误位置打印制表符和换行符,但代码的主要问题是数组索引和矩阵大小。您可以通过对行数和列数使用变量来轻松解决这个问题。
public class BusSeatReservation {
public static void main(String[] args) {
System.out.println("\t\t\tBUS SEAT RESERVATION");
int rows = 10;
int cols = 4;
char[][] matrix = new char[rows][cols];
System.out.print("\t\t");
for (int col = 0; col < cols; col++) {
System.out.print("\tCol " + (col+1));
}
System.out.println();
for (int row = 0; row < rows; row++) {
System.out.print("Row " + (row+1) + "\t|\t");
for (int seat = 0; seat < cols; seat++) {
matrix[row][seat] = '*';
System.out.print(matrix[row][seat] + "\t\t");
}
System.out.println();
}
}
}
我正在尝试使用二维数组进行座位预订。我遇到了一个问题,输出似乎不正确,我不知道如何处理它。我已经尝试了很多次,但仍然没有做对。我只想将星号放在 2d table 或行和列内。星号代表座位。
public class BusSeatReservation {
public static void main(String args[]) {
System.out.println("\t\t\t\tBUS SEAT RESERVATION");
char [][] matrix = new char [11][10];
for (int col = 1; col <= 4; col++) {
System.out.print("\t\tCol " + (col) + "\t");
}
System.out.println();
for (int row = 1; row <= 10; row++) {
System.out.println("Row " + (row) + "\t|");
for (int seat = 1; seat <= 4; seat++) {
matrix [row] [seat] = '*';
System.out.print(matrix [row] [seat] + "\t\t");
}
}
System.out.println();
}
}
问题是您在循环内的错误位置打印制表符和换行符,但代码的主要问题是数组索引和矩阵大小。您可以通过对行数和列数使用变量来轻松解决这个问题。
public class BusSeatReservation {
public static void main(String[] args) {
System.out.println("\t\t\tBUS SEAT RESERVATION");
int rows = 10;
int cols = 4;
char[][] matrix = new char[rows][cols];
System.out.print("\t\t");
for (int col = 0; col < cols; col++) {
System.out.print("\tCol " + (col+1));
}
System.out.println();
for (int row = 0; row < rows; row++) {
System.out.print("Row " + (row+1) + "\t|\t");
for (int seat = 0; seat < cols; seat++) {
matrix[row][seat] = '*';
System.out.print(matrix[row][seat] + "\t\t");
}
System.out.println();
}
}
}