Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Seats Reservation

I am trying to make a seat reservation using the 2d arrays. I’ve got a problem wherein the output doesn’t seem right and I don’t know what to do with it. I’ve tried it multiple times but still doesn’t get it right. I just want to put the asterisk inside the 2d table or inside the rows and columns. The asterisk represents as the seats.

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

and that was the output of my code

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem is that you are printing tabulators and new lines at the wrong places within the loops but the major problem with your code are the array indices and matrix size. You can easily solve that by using variables for number of rows and columns.

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

    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading