我正在嘗試使用二維陣列進行座位預訂。我遇到了一個問題,其中輸出似乎不正確,我不知道如何處理它。我已經嘗試了很多次,但仍然沒有正確。我只想將星號放在二維表內或行和列內。星號代表座位。
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();
}
}

uj5u.com熱心網友回復:
問題是您在回圈中的錯誤位置列印制表符和新行,但您的代碼的主要問題是陣列索引和矩陣大小。您可以通過使用變數來表示行數和列數來輕松解決這個問題。
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();
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/407752.html
標籤:
下一篇:FusedLocationProviderClient崩潰并出現java.lang.NullPointerException:指定為非null的引數位置為null
