3
\$\begingroup\$

I have completed my lab assignment for class, but I'm still wondering if there's any ways I could better optimize my code. specifically my methods isSeatAvailable and reserveSeat. Here is my problem: Write a program that displays, examines and manipulates a two dimensional array representing plane seats for a plane with 12 rows and 4 seats per row. Write methods for the following operations:

fillSeatsRandomly:Fills the array with random values in range from 0 to 1. Zero represents an empty seat and one represents a reserved seat.

displaySeats: Displays all the seats in the plane row by row. Empty seat is displayed as 0 and a reserved seat is displayed as X. Create vertical headings for the row numbers from 1 to 12 on the left hand side and horizontal column headings from A to D (for the 4 seats in the row).

isSeatAvailable: Receives an integer representing a row number and a character representing a seat from A to D. This method tests if the specified seat is available, otherwise it returns false. This method displays an error message when the seat selection is invalid.

reserveSeat: Reserves a specified seat. Receives two parameters: an integer representing a row number and a character representing a seat number from A to D. This method displays an error message when the seat is invalid.

seatsAvailInRow: counts and returns number of seats available in given row. Receives an integer representing row number.

findRowWithTwoSeats: This method look for the closest row with two adjacent available seats. If two adjacent seats are not available it returns 0.

countSeatsAvail: counts the number of all seats available in the plane and returns that number.

countTakenSeats: counts the number of all seats reserved in the plane and returns that number.

Here is my code:

public class ArraysLab {

    public static void main(String[] args) {
        Plane p = new Plane();
        p.fillSeatsRandomly();
        p.displaySeats();
        if (p.isSeatAvailable(2, 'B')) {
            System.out.println("You have reserved seat: 2,B");
            p.reserveSeat(2, 'B');
            p.displaySeats();
        }
        System.out.println("Sorry, seat: 2,B is already taken");
        System.out.println("There is " + p.seatsAvailInRow(5)
                + " seat(s) available in row 5");
        System.out.println("Row " + p.findRowWithTwoSeats()
                + " has 2 adjacent seats");
        System.out.println("Seats available: " + p.countSeatsAvail());
        System.out.println("Seats taken: " + p.countTakenSeats());
    
    }//end of main

}//end of class ArraysLab

class Plane {

    int[][] seats = new int[12][4];

    public void fillSeatsRandomly() {//fills seats randomly
        for (int[] seats1 : seats) {
            for (int col = 0; col < seats1.length; col++) {
                seats1[col] = (int) Math.round(Math.random());
            }//end of nested for
        }//end of for
    }//end of fill seats randomly

    public void displaySeats() {//displays the seats
        System.out.print("\tA  \tB  \tC  \tD \n");
        for (int row = 0; row < seats.length; row++) {
            System.out.print(row + 1 + "");
            for (int seatNum = 0; seatNum < seats[row].length; seatNum++) {
                if (seats[row][seatNum] == 1) {
                    System.out.print("\tX  ");
                } else {
                    System.out.print("\t0  ");
                }
            }//end of nested for
            System.out.println();
        }//end of for
    }//end of displaySeats

    public boolean isSeatAvailable(int row, char column) {  //checks if seat is 
        //available, returns true if it is and false if not
        int rowNum = row - 1;//row number of the seat chosen
        char colChar = column;//character of the seat chosen
        int colNum = 0;//char converted to int for ease of use
        switch (colChar) {
            case 'A':
                colNum = 0;
                break;
            case 'B':
                colNum = 1;
                break;
            case 'C':
                colNum = 2;
                break;
            case 'D':
                colNum = 3;
        }
        //end of switch
        return seats[rowNum][colNum] == 0;
    }//end of isSeatAvail

    public void reserveSeat(int row, char column) {//reserves a seat updates array
        int rowNum = row - 1;//Row number of seat chosen
        int colNum = 0;//Column number of seat chosen
        char seatSelect = column;//Character of column chosen
        switch (seatSelect) {
            case 'A':
                colNum = 0;
                break;
            case 'B':
                colNum = 1;
                break;
            case 'C':
                colNum = 2;
                break;
            case 'D':
                colNum = 3;
        }//end of switch
        seats[rowNum][colNum] = 1;
    } //end of reserveSeat

    public int seatsAvailInRow(int row) {//checks how many seats are available 
        //in a row determined returns int value
        int rowNum = row - 1;
        int rowSum = 0;
        int avail;
        for (int[] plane1 : seats) {
            rowSum = 0;
            for (int j = 0; j < plane1.length; j++) {
                rowSum += seats[rowNum][j];
            } //end of nested for
        } //end of for
        avail = 4 - rowSum;
        return avail;//returns number of seats available
    }//end of seatsAvailInRow

    public int findRowWithTwoSeats() {//finds the closest row that has 
        //2 adjacent seats, returns row num, or 0 if none
        for (int i = 0; i < seats.length; i++) {
            for (int j = 0; j < seats[i].length; j++) {
                if (seats[i][0] + seats[i][1] == 0 || seats[i][1]
                        + seats[i][2] == 0
                        || seats[i][2] + seats[i][3] == 0) {
                    return i + 1;//returns row num with adjacent seats
                }//end of if
            } //end of nested for
        } //end of for
        return 0;//returns 0 if there is no adjacent seats
    }//end of findRowWithTwoSeats

    public int countSeatsAvail() {//counts how many seats are available on the
        //plane, returns int value
        int count = 0;//used to keep track of how many seats are available
        for (int[] plane1 : seats) {
            for (int j = 0; j < plane1.length; j++) {
                if (plane1[j] == 0) {
                    count++;
                } //end of if
            } //end of nested for
        } //end of for
        return count;//returns the number of seats available
    }//end of countSeatsAvail

    public int countTakenSeats() {//counts number of seats taken on the plane, 
        //returns int value
        int count = 0;//used to keep track of how many seats are taken
        for (int[] plane1 : seats) {
            for (int j = 0; j < plane1.length; j++) {
                if (plane1[j] == 1) {
                    count++;
                }
            } //end of nested for
        } //end of for
        return count;//returns number of seats taken
    }//end of countTakenSeats
}//end of class plane
\$\endgroup\$

1 Answer 1

4
\$\begingroup\$

You can improve your code in multiple ways:

  1. I believe you are using at least Java 8 version, so consider using Stream API for iteration. (please take example from enum static block)

  2. Remove duplicate code or your code. Extract duplicate code in another private method. Like : isSeatAvailable and reserveSeat uses same switch code. And countSeatsAvail and countTakenSeats use almost same logic only one condition is different. (Added updated code below, where I have used Lambda to avoid code duplication)

  3. Method names should have consistency like countSeatsAvail and countTakenSeats should be like countTakenSeats and countAvailSeats. (updated code with change is added, these method are not needed any more)

  4. Avoid using abbreviations for names like Available to Avail. Until unless it's well-known abbreviation or it makes method too long.

  5. Avoid unnecessary variable creation like in reserveSeat and isSeatAvailabe assign column to seatSelect and colChar variable. Even the names should have consistency as they indicate same value.

  6. You can avoid these switch cases condition with enum. (updated code with change is added and you don't need it anymore)

  7. Method name should be clear to give the method details as seatsAvailInRow should be rather adjusentSeatsAvailableInRow.

  8. You can avoid these unwanted comments on each and every line. (ex endOfIf, endOfFor, endOfMethod etc.)


package test.file;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.IntPredicate;

public class LatestClass {

  public static void main(final String[] args) {
    final Plane p = new Plane();
    p.fillSeatsRandomly();
    p.displaySeats();
    if (p.isSeatAvailable(2, 'B')) {
      System.out.println("You have reserved seat: 2,B");
      p.reserveSeat(2, 'B');
      p.displaySeats();
    }
    System.out.println("Sorry, seat: 2,B is already taken");
    System.out.println("There is " + p.seatsAvailInRow(5) + " seat(s) available in row 5");
    System.out.println("Row " + p.findRowWithTwoSeats() + " has 2 adjacent seats");
    System.out.println("Seats available: " + p.countSeats(panel -> panel == 0));
    System.out.println("Seats taken: " + p.countSeats(panel -> panel == 1));
  }
}

class Plane {

  int[][] seats = new int[12][4];

  public int countSeats(final IntPredicate condition) {//counts how many seats are available on the
    //plane, returns int value
    int count = 0;//used to keep track of how many seats are available
    for (final int[] plane1 : seats) {
      for (int j = 0; j < plane1.length; j++) {
        if (condition.test(plane1[j])) {
          count++;
        } //end of if
      } //end of nested for
    } //end of for
    return count;//returns the number of seats available
  }

  public void displaySeats() {//displays the seats
    System.out.print("\tA  \tB  \tC  \tD \n");
    for (int row = 0; row < seats.length; row++) {
      System.out.print(row + 1 + "");
      for (int seatNum = 0; seatNum < seats[row].length; seatNum++) {
        if (seats[row][seatNum] == 1) {
          System.out.print("\tX  ");
        } else {
          System.out.print("\t0  ");
        }
      } //end of nested for
      System.out.println();
    } //end of for
  }//end of displaySeats

  public void fillSeatsRandomly() {//fills seats randomly
    for (final int[] seats1 : seats) {
      for (int col = 0; col < seats1.length; col++) {
        seats1[col] = (int) Math.round(Math.random());
      } //end of nested for
    } //end of for
  }//end of fill seats randomly

  public int findRowWithTwoSeats() {//finds the closest row that has
    //2 adjacent seats, returns row num, or 0 if none
    for (int i = 0; i < seats.length; i++) {
      for (int j = 0; j < seats[i].length; j++) {
        if (seats[i][0] + seats[i][1] == 0 || seats[i][1] + seats[i][2] == 0 || seats[i][2] + seats[i][3] == 0) {
          return i + 1;//returns row num with adjacent seats
        } //end of if
      } //end of nested for
    } //end of for
    return 0;//returns 0 if there is no adjacent seats
  }//end of findRowWithTwoSeats

  public boolean isSeatAvailable(final int row, final char colChar) { //checks if seat is
    //available, returns true if it is and false if not
    final int rowNum = row - 1;//row number of the seat chosen
    final int colNum = SeatColumn.getColumn(colChar);
    //end of switch
    return seats[rowNum][colNum] == 0;
  }//end of isSeatAvail

  public void reserveSeat(final int row, final char seatSelect) {//reserves a seat updates array
    final int rowNum = row - 1;//Row number of seat chosen
    final int colNum = SeatColumn.getColumn(seatSelect);
    seats[rowNum][colNum] = 1;
  } //end of reserveSeat

  public int seatsAvailInRow(final int row) {//checks how many seats are available
    //in a row determined returns int value
    final int rowNum = row - 1;
    int rowSum = 0;
    int avail;
    for (final int[] plane1 : seats) {
      rowSum = 0;
      for (int j = 0; j < plane1.length; j++) {
        rowSum += seats[rowNum][j];
      } //end of nested for
    } //end of for
    avail = 4 - rowSum;
    return avail;//returns number of seats available
  }//end of seatsAvailInRow
}//end of class plane

enum SeatColumn {
  A(0), B(1), C(2), D(3);

  private static final Map<Character, Integer> seatColumnMapping = new HashMap<>();

  static {
    Arrays.stream(values()).forEach(v -> {
      seatColumnMapping.put(Character.valueOf(v.toString().charAt(0)), Integer.valueOf(v.column));
    });
  }

  private int column;

  SeatColumn(final int column) {
    this.column = column;
  }

  public static int getColumn(final char seat) {
    return seatColumnMapping.get(Character.valueOf(seat)).intValue();
  }

  public int getColumn() {
    return column;
  }

}
\$\endgroup\$
1
  • \$\begingroup\$ Nice answer. When you edit a question it is better not to edit the code. \$\endgroup\$
    – pacmaninbw
    Nov 26, 2020 at 13:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.