Kevin Xie
Kevin Xie

Reputation: 45

implementing a method from one class to another?

I am making a program for airplane seating arrangements for a class and i ended up making two toString methods but when I run the program the toString method in my airplane class is making something not work specifically:

str= str + seats[i][j].toString();

I believe that simply deleting the toString method in the seat class and somehow putting it back into the airplane class toString method would fix the problem or make it simpler. What's wrong?

Airplane class:

public class Airplane 
{
  private Seat [ ] [ ] seats;
  public static final int FIRST_CLASS = 1;
  public static final int ECONOMY = 2;
  private static final int FC_ROWS = 5;
  private static final int FC_COLS = 4;
  private static final int ECONOMY_ROWS = 5;
  private static final int ECONOMY_COLS = 6;

  public Airplane() 
  {
    seats  = new Seat[FC_ROWS][ECONOMY_COLS]; 
  }
  public String toString()
  {
    String str = "";
    for (int i=0; i<FC_ROWS; i++) {
      for (int j=0; j<ECONOMY_COLS; j++) 
      {
        str= str + seats[i][j].toString();
      }
      str = str + "\n";
    }
    return str;
  }   

}

Seat Class:

public class Seat 
{
  private int seatType;
  private boolean isReserved;
  public static final int WINDOW = 1;
  public static final int AISLE = 2;
  public static final int CENTER = 3;

  public Seat(int inSeatType)
  {
    seatType = inSeatType;
    isReserved = false;
  }
  public int getSeatType()
  {
    return seatType;
  }

  public void reserveSeat()
  {
    isReserved = true;
  }
  public boolean isAvailable()
  {
    if (!isReserved)
    {
      return true;
    }
    else return false; 
  }
  public String toString()
  {
    if(isReserved == false)
    {
      return "*";
    }
    else return "";
  }
}

Upvotes: 0

Views: 170

Answers (3)

durron597
durron597

Reputation: 32323

  • In Seat.toString you should print a " " not "".
  • You're array is FC_ROWS by ECONOMY_COLS, so you're not creating all the seats. You should probably have two arrays (one for FC, one for Economy), since FC_ROWS != ECONOMY_ROWS.
  • You aren't actually creating Seats in your constructor. Use a nested loop to create them, otherwise you will get a NullPointerException. Creating an array doesn't create the objects contained in the array.
    • When you're creating the seats in the Airplane constructor, use if statements to figure out if the seat is supposed to be a Window, Aisle, etc.

Upvotes: 1

Wanbok Choi
Wanbok Choi

Reputation: 5452

seats seems to does not have Seat's instance.

Add this code :

for (int i=0; i<FC_ROWS; i++) {
    for (int j=0; j<ECONOMY_COLS; j++) 
    {
        seats[i][j] = new Seat();
    }
}

below this :

seats  = new Seat[FC_ROWS][ECONOMY_COLS];

Upvotes: 1

ebsddd
ebsddd

Reputation: 1026

I think that in Seat::toString, you mean to return " " (a space) if it isn't reserved.

Upvotes: 0

Related Questions