-1

I want to build a Bus seat service. Like: Seat

 1A 1B 1C 1D
 2A 2B 2C 2D
 3A 3B 3C 3D
 3A 3B 3C 3D
 4A 4B 4C 4D 
 5A 5B 5C 5D 
 6A 6B 6C 6D 
 7A 7B 7C 7D 

Depending of number rows the user want to insert.

My code works well but I would like to improve it. Any suggestion will be so nice. Note: I hate the way I wrote nested for loop with no braces.

code:

static void busRow(int numberOfRows){
    String letters[] = {"A","B","C","D"};
    if (numberOfRows<=0){
        System.out.println("Without Seats? It isn't a bus! please insert number of rows");
    }

    for (int i =1; i<=numberOfRows;i++){
        for (int j =0;j<letters.length;j++)
            System.out.print(i+""+letters[j]+" ");
        System.out.println();
    }

}
Eddy Bayonne
  • 2,448
  • 1
  • 17
  • 23

2 Answers2

2

The program is relatively simple and well written, there also aren't many changes that can be made to two nested for loops. You've maintained good programming practices with indentation and braces, so there isn't much to improve on!

You could try creating useful functions such as seat reservation or deletion, that could be of use to you. For example, a user wants to sit in seat 2B. You could capture the input from the user and "reserve" the seat with an X so your row would then look as follows:

2A X 2C 2D

Gilad Tabul
  • 23
  • 1
  • 5
2

Your nested for loop is as efficient as you are going to get as far as the seat generating algorithm.

The only slight change I would suggest is to change your letters array from String[] to char[] assuming that all seat labels are single character letters. This change is very slight but the reasoning for this is that because a char is a primitive data type and only takes up 2 bytes whereas a String is an actual object and, even when empty, requires at least 32 bytes.

This is a very particular change which won't offer you much a significant change in this example, but its a practice I think that would benefit coding in the future where every byte might count.

Hope this is of some worth!

Reference:

How much memory does a string use in Java 8?

Martin Navarro
  • 574
  • 4
  • 10