Solved

Recording  plane seats taken !!!

Posted on 2000-04-02
15
949 Views
Last Modified: 2008-02-04
I have got myself stuck. How do i keep track of seats . First class has only 5 rows of 4 seats so an array [x][y] with y values of 1 or 2 will be the aisle seats and 0 and 3 will be window seats.
 But how do i record the values on disk. At the moment how i am doing it I will need to have  a seperate file for First class Aisle seats, First class Window seats, Economy Aisle, economy Centre ,Economy window. 5 seperate files to record a 1 if taken or 0 if vacant. a sample of the code is below ,
it is accesed only if the passenger has requested a First Class("f") Aisle("a")seat. It isnt writing yet but don't even look at it as i am sure my whole idea is terrible. Would using a Seat object/class enable me to use only one file somehow ?? Any ideas please.




public static boolean getPassengerfSeat(String seatPref)throws IOException
    {
       int[][] firstClassSeats = new int[5][4];
     //if this returns true let writeMyFile() know it !!!!!!
     DataInputStream in = new DataInputStream(new FileInputStream("a:pArray.dat"));
     int num = 0;
     int x, y;
     boolean found = false;
     for (x = 0; x < 5; ++x) { //3
       for (y = 0; y < 4; ++y) {//2
        if (y == 1 ||y == 2) {//1
        try{
        num = in.readInt();
        firstClassSeats[x][y]= num;
        }
        catch(IOException ioe){
        }
         if(firstClassSeats[x][y]!=0){
         System.out.println("Re-Enter Passenger :-- there is NO seat in First Class Aisle");
         }
         if(firstClassSeats[x][y]==0){
         System.out.println("there is a seat in Fist class Aisle");
          DataOutputStream out = new DataOutputStream(new FileOutputStream("a:pArray.dat",true));

         try{

         out.writeInt(firstClassSeats[x][y]= 1 );
         }
         catch(IOException e){
         }

           found = true;
          break;                            }
        }//1
       }//2
         if(found == true) {

          break;

         }
    } //3



      return found;
    }
0
Comment
Question by:norfarm
  • 8
  • 6
15 Comments
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2678613
This isn't very helpful but I feel as if I need to remind you that I suggested on a previous question about making Passenger persistent that your problem was going to be bigger than just how to serialize an object to a file.

Another less than helpful suggestion/question: Are you working from a design or are you pounding this out as you go? It sounds to me like you really need to take a step back from the implementation, review your requirements (assuming they are written down somewhere), and start thinking about what classes naturally occur in your problem domain. What are their responsibilities, what are the relationships, and how do they collaborate together to solve the problems presented in your requirements. If the requirements don't define the functionality of this system, you might consider writing some simple use cases (interaction scenarios between users and your system) to help jump start this. Analyzing the requirements and your scenarios, nouns will help you identify candidate classes, adjectives candidate attributes, and verbs candidate operations.

These are the first steps to OO analysis and design. Don't do them at your peril.

Best regards -- but no answers,
Jim Cakalic
0
 

Author Comment

by:norfarm
ID: 2679400
Thanks for reply I will post a follow up to this  which may make an answer easer to post. I am after any kind of way to keep trak of vacant seats as i can only do this with my current skills if no File writing reading is reqired and this is an urgent job. the rest of my beta code for my program is already done. I dont think i would find this any easier ifr i was writing files in VB ,c ,cobol or any language. My abstact thinking is bad.If i can solve this ill be able to write a lot of other programs needing this kind of problem .My boss wants it done by the 10th april, yikes !!
0
 
LVL 7

Expert Comment

by:Sasha_Mapa
ID: 2679466
Sounds like plenty of time to rethink/rewrite it as jim said... :-)
0
 

Author Comment

by:norfarm
ID: 2679511
can we forget about OO programming and do it the old way ,procedural programming, Ive no OO programing experence.(way behind  the times :(

I know no programmers ,a total recluse.
god im going to take a job in road construction before i have a breadown :)
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2680697
norfarm, I've got some time in the next few days. If you want to post or (better I think) email me your requirements, source code, and anything else you think might help, I will review it and see if I can make some useful suggestions.

Mail to jim_cakalic@na.biomerieux.com.

Best regards,
Jim Cakalic
0
 

Author Comment

by:norfarm
ID: 2694918
Airline Reservation

write a text based app.

Assume the airplane has 20 seatrs in first class (5 rows of 4 seats)separated by an aisle.
and 60 seats in economy class (10 rows of 6 seats each separated by an aisle)

Details of booked seats:(passebger first and last names, date booking was made(dd/mm/yy),
ticket price, seating class (F or E) seat row (1,2,3 etc) and seat position (A,B etc) are stored in a file.

Use 2 dimensional arrays to maintain the seating charts for each of seating classses.

When passengers are added, ask for the class (first or economy, the name of the passanger and the seating preference, Aisle ,window if first class  or aisle, centre ,window in economy class. Then try to find a match, assign the seat by updating the seating chart and then update the file

If no match exists (that is the seat is taken) display an appropriate message.
0
 
LVL 19

Accepted Solution

by:
Jim Cakalic earned 120 total points
ID: 2696683
norfarm,

Based on other posts I have seen on this forum, I'm pretty sure this is a class assignment. Some experts wouldn't respond to it. However, because I know that many people learn by examining the approach others have taken, I'm posting an infrastructure for solving this problem. This is probably much more than I should do but I think substantially enough of the problem remains unsolved (and enough of my code is untested) that you will still have to work to complete the assignment. There is certainly more than one way to solve this problem. And given different constraints, I'd likely take a different approach than I did here. That having been said ...

From the problem description, several classes jumped out at me: Airplane, SeatingClass, Seat, and Passenger. Pretty much everything else seemed to be attributes of these four classes.

Airplane knows it two seating classes and provides upper level assistance for the assignment of seats and printing of the passenger manifest.

SeatingClass creates and manages Seats. It can find an unassigned seat of the supplied seating preference      and collaborates in printing the manifest.

Seat knows its occupant of Passenger. It provides a reserve() method for establishing this relationship along with the price charged for the booking. The date of the booking is assumed to be the current date. It collaborates in printing the manifest by providing a toString() implementation appropriate to the task.

Passenger is the occupant. It knows first and last name and provides a toString() method that can be used for adding this detail to the manifest.

These four classes with initial implementation appear below. The final class is the TicketAgent which is where most of your implementation remains to be done. The text prompts, gathering and parsing user input, and acting upon the input need to be added. Object serialization and deserialization becomes fairly simple because all the objects are related to Airplane:

Airplane -- has 2 -- SeatingClass -- has many -- Seat -- has 1 -- Passenger

All the classes implement Serializable so all you have to do is serialize Airplane to a file and you're done. Serialization takes care of traversing the network of objects and getting them all written. I think Date and String are the only jdk objects I used and these both implement Serializable. Deserialize from the file when the program starts and you can work with the objects in memory as you please.

Note that creating a new Airplane creates all the necessary objects except the Passenger objects. These need to be created just prior to reserving a seat as shown in TicketAgent.reserveSeat().

One bell I stubbed in would allow for working with multiple airplanes as chosen by a command line argument which names the file that contains the serialized object Airplane object. You can choose not to implement this.

I hope that I have neither provided too much assistance nor too little. I think that the code is mostly self-explanatory. All the code compiles as is and basically runs -- although the only thing it does is print a manifest of unoccupied seats.

Good luck.
Jim Cakalic

---------- Airplane.java ----------
import java.io.Serializable;

public class Airplane implements Serializable {
    private SeatingClass firstClass;
    private SeatingClass economyClass;

    public Airplane() {
        // create seating classes of fixed size
        economyClass = new SeatingClass(10, 6);
        firstClass = new SeatingClass(5, 4);
    }

    public Seat assignSeat(int seatingClass, int preference) {
        if (seatingClass == SeatingClass.FIRST) {
            return firstClass.assignSeat(preference);
        } else if (seatingClass == SeatingClass.ECONOMY) {
            return economyClass.assignSeat(preference);
        } else {
            return null;
        }
    }

    public void printManifest() {
        System.out.println("First class:");
        firstClass.printManifest();
        System.out.println("Economy class:");
        economyClass.printManifest();
    }

}

---------- SeatingClass.java ----------
import java.io.Serializable;

public class SeatingClass implements Serializable {
    public static final int FIRST = 1;
    public static final int ECONOMY = 2;

    private Seat[][] seats;

    public SeatingClass(int rows, int seatsPerRow) {
        // Technically, we should require seatsPerRow to be even.
        // Assume that it is for this assignment
        seats = new Seat[rows][seatsPerRow];
        for (int i = 0; i < rows; ++i) {
            seats[i][0] = new Seat(Seat.WINDOW);
            for (int j = 1; j < seatsPerRow - 1; ++j) {
                boolean aisle = (j == (seatsPerRow / 2 - 1) || j == (seatsPerRow / 2 + 1));
                seats[i][j] = new Seat(aisle ? Seat.AISLE : Seat.CENTER);
            }
            seats[i][seatsPerRow - 1] = new Seat(Seat.WINDOW);
        }
    }

    public Seat assignSeat(int preference) {
        for (int i = 0; i < seats.length; ++i) {
            for (int j = 0; j < seats[0].length; ++j) {
                Seat seat = seats[i][j];
                if (seat.isPosition(preference) && seat.isReserved() == false) {
                    // Found an unoccupied seat matching the stated preference
                    return seats[i][j];
                }
            }
        }
        // No qualifying unoccupied seats found
        return null;
    }

    public void printManifest() {
        for (int i = 0; i < seats.length; ++i) {
            for (int j = 0; j < seats[0].length; ++j) {
                Seat seat = seats[i][j];
                // This needs a lot of work!!
                System.out.println(i + "-" + j + ": " + seat.toString());
            }
        }
    }

}

---------- Seat.java ----------
import java.io.Serializable;
import java.util.Date;

public class Seat implements Serializable {
    // Seating positions
    public final static int WINDOW = 1;
    public final static int CENTER = 2;
    public final static int AISLE = 3;

    private Passenger passenger;
    private Date bookingDate;
    private float ticketPrice;
    private int position;

    public Seat(int position) {
        this.position = position;
    }

    public boolean isReserved() {
        return passenger != null;
    }

    public void reserve(Passenger passenger, float price) {
        this.passenger = passenger;
        ticketPrice = price;
        bookingDate = new Date();
    }

    public Passenger getPassenger() {
        return passenger;
    }

    public Date getBookingDate() {
        return bookingDate;
    }

    public float getTicketPrice() {
        return ticketPrice;
    }

    public boolean isPosition(int preference) {
        return position == preference;
    }

    public String toString() {
        if (isReserved() == false) {
            return "unoccupied";
        }
        return passenger.toString();
    }
}

---------- Passenger.java ----------
import java.io.Serializable;

public class Passenger implements Serializable {
    private String lastName;
    private String firstName;

    public Passenger(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public String toString() {
        return lastName + ", " + firstName;
    }

}

---------- TicketAgent.java  ----------
public class TicketAgent {
    Airplane airplane;

    public TicketAgent() {
        airplane = new Airplane();
    }

    public void selectFlight(String[] args) {
        // Deserialize airplane from serialized file
        // Maybe take name of file from args?
        // Sets the airplane instance variable
    }

    public void interact() {
        // Loop asking for next choice: reserve seat, print manifest, quit
        // Method doesn't return until quit is chosen
        System.out.println("What do you want to do today?");
        printManifest();
    }

    public void updateFlight(String[] args) {
        // Serialize airplane to file
        // Maybe take name of file from args?
    }

    public void reserveSeat() {
        int seatingClass = SeatingClass.FIRST;
        int seatingPreference = Seat.AISLE;

        // Ask for class and seating preference

        Seat assignment = airplane.assignSeat(seatingClass, seatingPreference);
        if (assignment == null) {
            // apologize because no seats matching the preference
        } else {
            // ask for passenger name
            // set the price for the seat?
            // reserve this seat
            Passenger passenger = new Passenger("John", "Doe");
            float price = 1000.0f;
            assignment.reserve(passenger, price);
        }
    }

    public void printManifest() {
        airplane.printManifest();
    }

    public static void main(String[] args) {
        TicketAgent agent = new TicketAgent();
        agent.selectFlight(args);
        agent.interact();
        agent.updateFlight(args);
    }
}
---------- end ----------
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2704925
So your assignment was due yesterday, right? How'd you do? Did my post help?

Jim
0
 

Author Comment

by:norfarm
ID: 2704992
not yet jim, i rolled my car (front tire blew) so i got 10 days extra but i showed the code to a mate and he thinks im gona top the the whole class of 130 students :)

Ill let you know. Im way too il to do anything much at the moment.

thanks so much ,ill send you a cheque if you want, you did so much for me.

sincerely mike.
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2705060
No payment required :-) I participate on this list because I enjoy helping others, solving problems, and honing my own skills.

Sorry to hear about the accident. Take care and get well soon.

Best regards,
Jim Cakalic
0
 

Author Comment

by:norfarm
ID: 2713970
Jim, i am in big trouble, going to hospital today to get a brain scan, cause i cant concentrate for more than 5 min at a time.

with your program do i make , sorry lost the plot agin, later.

mike.
0
 

Author Comment

by:norfarm
ID: 2724532
Below is the code I wrote before asking questions. As you can see if you run it i will need 5 files to keep track of the seats.
Sorry that i dont understand your code very well. I really just want a way of saving the state of 2d arrays ???
I will try and persevere with your code though i find it quite difficult for a novice with many assignments due :(
I sincerely appreciated all your effort.

Mike.


import java.io.*;
import java.util.*;
public class Aero
{//1
 public static void main(String args[])throws IOException
 { //2
  int[][] firstClassSeats = new int[5][4];
  int[][] economyClassSeats = new int[10][6];

  performSwitch1();

  }//2
   public static void performSwitch1()throws IOException
   {  //3
    System.out.println("\n'A' add Passenger 'L' list Passengers 'Q' Quit");
    int action;
    action = 1;
    action = System.in.read();
    System.in.skip(2);
    switch(action){
    case 'a' :addPassengerInfo();break;//s l q still to go
    case 'l' :listPassengers();break;
    //case 3 :showSeating();break;
    case 'q' :System.exit(1);break;
    default:performSwitch1();break;
    }
   }//3
   public static void addPassengerInfo() throws IOException
   {//4
    String fname;    //this supposed to get all info of passenger
    String lname;
    String seatPref;
    String pClass;
    double ticketAmt;
    boolean seatTrue = true;
    File output = new File("a:passengers.dat");
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    //System.out.println("\nPlease enter date XX/XX/XXXX");

    System.out.println("\nPlease enter Passenger first name");
    fname = getString(in);
     System.out.println("\nPlease enter Passenger Last name");
    lname = getString(in);
    System.out.println("\nPlease enter passenger Class 'F' or 'E'");
    pClass = getString(in);
    System.out.println("\nPlease enter seat preference 'A'isle  'C'entre  'W'indow");
    seatPref = getString(in);
    System.out.println("\nTicket price $");
    ticketAmt = getMyDouble(in);
    if(pClass.equals("e")){
    getPassengerESeat(seatPref);
    }
    if(pClass.equals("f")){
    getPassengerfSeat(seatPref);
    }
    //seatTrue = getPassengerfSeat(pClass,seatPref)
    writeMyFile(fname,lname,seatPref,ticketAmt);
    performSwitch1();
  }//4
    public static String getString(BufferedReader in)
    {
     String name = " ";

      try {
      name = in.readLine();
      name = name.trim();
      }
      catch(IOException e){
      }
      return name;
    }
    public static double getMyDouble(BufferedReader in)
    {
      String name = " ";
      double ticketAmt = 0.0;
      try {
      name = in.readLine();
      name = name.trim();
      ticketAmt = Double.valueOf(name).doubleValue();
      }
      catch(IOException e){
      }
      return ticketAmt;
    }

    public static void writeMyFile(String fname,String lname,
    String seatPref,double ticketAmt)
    {
     try{


DataOutputStream out = new DataOutputStream(new FileOutputStream("a:p.dat", true));

     out.writeUTF(fname);
     out.writeUTF(lname);
     out.writeUTF(seatPref);
     out.writeDouble(ticketAmt);
     out.close();

     }
      catch(IOException e){
      }
    }
    public static void listPassengers()throws IOException
    {
     String fname ="";
     String lname = "";
     String seatPref ="";
     double ticketAmt = 0;
DataInputStream in = new DataInputStream(new FileInputStream("a:p.dat"));
    try{
      while(true){
      fname = in.readUTF();
      lname = in.readUTF();
      seatPref = in.readUTF();
      ticketAmt = in.readDouble();
      System.out.println("\n" + fname + " " + lname + " " + seatPref + " " + ticketAmt);
      }
     }
     catch(IOException eof){
     }
     performSwitch1();
    }

    public static boolean getPassengerfSeat(String seatPref)throws IOException
    {
       int[][] firstClassSeats = new int[5][4];
     //if this returns true let writeMyFile() know it !!!!!!
     DataInputStream in = new DataInputStream(new FileInputStream("a:pArray.dat"));
     int num = 0;
     int x, y;
     boolean found = false;
     for (x = 0; x < 5; ++x) { //3
       for (y = 0; y < 4; ++y) {//2
        if (y == 1 ||y == 2) {//1
        try{
        num = in.readInt();
        firstClassSeats[x][y]= num;
        }
        catch(IOException ioe){
        }
         if(firstClassSeats[x][y]!=0){
         System.out.println("Re-Enter Passenger :-- there is NO seat in First Class Aisle");
         }
         if(firstClassSeats[x][y]==0){
         System.out.println("there is a seat in Fist class Aisle");
          DataOutputStream out = new DataOutputStream(new FileOutputStream("a:pArray.dat",true));

         try{

         out.writeInt(firstClassSeats[x][y]= 1 );
         }
         catch(IOException e){
         }

           found = true;
          break;                            }
        }//1
       }//2
         if(found == true) {

          break;

         }
    } //3



      return found;
    }
         public static boolean getPassengerESeat(String seatPref)throws IOException
    {
       int[][] firstClassSeats = new int[5][4];
     //if this returns true let writeMyFile() know it !!!!!!
     DataInputStream in = new DataInputStream(new FileInputStream("a:pArray.dat"));
     int num = 0;
     int x, y;
     boolean found = false;
     for (x = 0; x < 5; ++x) { //3
       for (y = 0; y < 4; ++y) {//2
        if (y == 0 ||y == 3) {//1
        try{
        num = in.readInt();
        firstClassSeats[x][y]= num;
        }
        catch(IOException ioe){
        }
         if(firstClassSeats[x][y]!=0){
         System.out.println("Re-Enter Passenger :-- there is NO Window seat in first class");
         }
         if(firstClassSeats[x][y]==0){
         System.out.println("there IS a Window seat in First Class");
          DataOutputStream out = new DataOutputStream(new FileOutputStream("a:pArray.dat",true));

         try{

         out.writeInt(firstClassSeats[x][y]= 1 );
         }
         catch(IOException e){
         }

           found = true;
          break;                            }
        }//1
       }//2
         if(found == true) {

          break;

         }
    } //3



      return found;
    }
}
0
 
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2759501
Mike,

How did you do on your assignment? I hope you were able to complete it.

Are you doing better since your accident?

Jim
0
 

Author Comment

by:norfarm
ID: 2759831
Ta for the note jim,
I am only beginning to get back into it.
I handed in what i had done myself ,however i will keep your code and get it to run properly when i get the hang of objects and serilizationetc.
 I must say that I never expected anyone to do so much but I am very humbled /gratious that you did put in such an  effort. It will come in handy for assignment two :-)

sincerely mike.
0
 

Author Comment

by:norfarm
ID: 2762861
Jim,

your e-mail keeps being returned to me ,!

do you have another email address ??

jim_cakalic@na.biomerieux.com

mike.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
for i loop in grovy 1 34
JAVA part two 5 42
maven example error 3 36
sites similar to codingbat to improve coding hanson skills 3 25
For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now