【问题标题】:Seats Reservation [closed]座位预订[关闭]
【发布时间】:2022-01-10 21:30:03
【问题描述】:

我正在尝试使用二维数组进行座位预订。我遇到了一个问题,其中输出似乎不正确,我不知道如何处理它。我已经尝试了很多次,但仍然没有正确。我只想将星号放在二维表内或行和列内。星号代表座位。

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

【问题讨论】:

    标签: java arrays multidimensional-array


    【解决方案1】:

    问题是您在循环中的错误位置打印制表符和新行,但您的代码的主要问题是数组索引和矩阵大小。您可以通过使用行数和列数的变量轻松解决这个问题。

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

    【讨论】:

    • 好吧,谢谢。我可以知道你为什么把它设为“(row+1)”和“(col+1)”吗??
    • Java 中的数组索引从零开始,但您尝试打印“Row 1”或“Col 1”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多