-
-
Save claudey/3991221 to your computer and use it in GitHub Desktop.
A full of bugs, unoptimized Java code for a CLI airline reservation.. Everything was built to be static. You may make it better or use the methods elsewhere.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package airlinereservationsystem_yawboakyeyiadom; | |
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.io.FileWriter; | |
import java.io.IOException; | |
import java.util.InputMismatchException; | |
import java.util.Scanner; | |
/** | |
* | |
* @author yaw | |
*/ | |
public class AirlineReservation { | |
/** | |
* @param args | |
*/ | |
private static Scanner sc = new Scanner(System.in); | |
private static boolean changesMadeToFile = false; | |
//all the seats in the aero plane | |
private static String[][] seats = new String[70][8]; | |
private static String destination = null; | |
private static String[] seat = null; | |
private static double[] ticketPrices = new double[2]; | |
private static double total; | |
private static String firstname = null; | |
private static String lastname = null; | |
private static int age = 0; | |
//the directory containing all the files | |
private static String parent = "src/airlinereservationsystem_yawboakyeyiadom/files/"; | |
public static void main(String[] args) { | |
String emptySeats = null; | |
boolean seatsAvailable = false; | |
String[][] noFly = new String[31][2]; | |
while(true) { | |
System.out.println("Welcome to the Airline Reservation System!\n"); | |
System.out.print("Are you a customer or a gate agent? "); | |
String clientType = sc.next(); | |
String oldDestination = destination; | |
try { | |
getTicketPrices(); | |
destination = getRoute(clientType); | |
} catch (InputMismatchException ex) { | |
System.out.println("\nThe route you chose does not exist.\n"); | |
if(tryAgain()) { | |
continue; | |
} else { | |
//sc.close(); | |
System.exit(0); | |
} | |
} catch (IOException e) { | |
System.out.println(); | |
} catch (Exception ex) { | |
if(tryAgain()) { | |
continue; | |
} | |
System.exit(0); | |
} | |
//at this point in execution, read the file just once for the mean time. Another read is only required | |
//if the destination (route) is changed e.g. change of route of ACC to KUM to ACC to TAM. if this isn't the | |
//initial run of the program, check to see if reservations were made in the former route and take appropriate | |
//actions | |
if(destination != null && !(destination.equals(oldDestination))) { | |
if(changesMadeToFile) { | |
saveToFile(oldDestination); | |
changesMadeToFile = false; | |
} | |
try { | |
populateFlightDatabase(destination, seats); //read from a file and save in the seats array | |
emptySeats = emptySeatsAvailable(seats); | |
seatsAvailable = emptySeats.length() > 0; | |
} catch (IOException e) { | |
//reading file content into RAM failed... | |
//aero plane is empty and waiting for reservations | |
System.err.println("Sorry. I think this plane is not ready for boarding yet because I couldn't\n" + | |
"get a list of all the reservations already made. Come again in about 30 minutes time. " + | |
"Thank you"); | |
System.exit(0); | |
} | |
} | |
if(isAnswer("customer", clientType) || isAnswer("gate agent", clientType) || isAnswer("agent", clientType)) { | |
if(changesMadeToFile) { | |
saveToFile(destination); | |
} | |
System.out.printf("\nYou are now in the %s menu. What will you like to do for today?\n", getRouteName()); | |
} | |
if(isAnswer("customer", clientType)) { | |
//get customer's choice of service | |
String customerChoice = customerMenu(); | |
switch(customerChoice) { | |
case "1": | |
if(seatsAvailable) { | |
printAvailableSeats(seats); | |
} else { | |
//there are no empty seats :( | |
System.out.println("There are no seats available on this flight. Thank you."); | |
} | |
break; | |
case "2": | |
if(seatsAvailable) { | |
makeReservation(seats); | |
} else { | |
//there are no empty seats. No reservations can be made :( | |
System.out.println("There are no seats available on this flight. Thank you."); | |
} | |
break; | |
case "3": | |
printBoardingPass(); | |
break; | |
case "4": | |
printReceipt(); | |
break; | |
case "5": | |
try { | |
changeSeatAssignment(); | |
} catch (Exception e) { | |
System.out.println("\nDear customer, an error encountered prevented your change of seat.\n"); | |
} | |
break; | |
default: | |
System.out.println("\nThe option you chose is not available on the menu.\n"); | |
} | |
System.out.println(); //create a blank line between consecutive transactions | |
} else if(isAnswer("agent", clientType) || isAnswer("gate agent", clientType)) { | |
//client is a gate agent | |
String agentChoice = agentMenu(); | |
switch(agentChoice) { | |
case "1": | |
checkNoFlyList(noFly); | |
break; | |
case "2": | |
performUpgrade(); | |
break; | |
case "3": | |
printPassengerRoster(); | |
break; | |
case "4": | |
printSalesReport(); | |
break; | |
default: | |
System.out.println("\nYour choice is not available on the menu. " + | |
"Please choose an option on the menu.\n"); | |
} | |
} | |
if(tryAgain()) { | |
continue; | |
} | |
break; | |
} | |
} | |
private static void printSalesReport() { | |
double firstClassSales = 0.0, economyClassSales = 0.0; | |
for(String[] s : seats) { | |
if(!isEmpty(s)) { | |
if(s[7].equalsIgnoreCase("first")) { | |
firstClassSales += ticketPrices[1]; | |
} else if(s[7].equalsIgnoreCase("economy")) { | |
economyClassSales += ticketPrices[0]; | |
} | |
} | |
} | |
System.out.printf( | |
"\nTOTAL TICKET SALES FOR ACC to %s\n" + | |
"---------------------------------\n" + | |
"%-12s : %.2f GHc\n" + | |
"%-12s : %.2f GHc\n\n" + | |
"%-12s : %.2f GHc\n" + | |
"---------------------------------\n\n", | |
getRouteName(), "First Class", firstClassSales, "Economy", economyClassSales, | |
"Total", firstClassSales + economyClassSales | |
); | |
} | |
private static void printPassengerRoster() { | |
System.out.printf( | |
"\nPassenger roster for ACC to %s\n" + | |
"-------------------------------\n", | |
getRouteName() | |
); | |
System.out.printf( | |
"\n%-3s\t| %-3s\t| %-20s\t| %-20s\t| %-3s\t| %s\t| %s\t| %s\n\n", | |
"row", "seat", "first", "last", "age", "exit row flag", "seat position", "ticket class" | |
); | |
for(String[] passenger : seats) { | |
System.out.printf( | |
"%-3s\t| %-3s\t| %-15s\t| %-15s\t| %-3s\t| %-6s\t| %-7s\t| %s", | |
passenger[0], passenger[1], passenger[2], passenger[3], passenger[4], passenger[5], | |
passenger[6], passenger[7] | |
); | |
System.out.println(); | |
} | |
System.out.println(); | |
} | |
private static void performUpgrade() { | |
//check all empty seats available in the first class.. | |
//if there's none available, exit the operation. No upgrade can be performed | |
String[] emptyFirstClassSeats = getClassEmptySeats("first"); | |
if(emptyFirstClassSeats == null) { | |
System.out.println("\nThere are no available seats for upgrade.\n"); | |
return; | |
} | |
Scanner u_input = new Scanner(System.in); | |
System.out.print("Please enter passenger last name: "); | |
String[] foundPassenger = findPassengerByLastName(u_input.nextLine()); | |
if(foundPassenger != null) { | |
String firstname = foundPassenger[2]; | |
String lastname = foundPassenger[3]; | |
if(foundPassenger[7].equalsIgnoreCase("first")) { | |
System.out.println("\nUpgrade can be performed for customers in economy class only.\n"); | |
return; | |
} | |
System.out.printf("\n%s %s is currently sitting in %s.\n\n", | |
firstname, lastname, foundPassenger[0]+foundPassenger[1].toUpperCase()); | |
System.out.println("Here are available first class seats:\n"); | |
displaySeats(emptyFirstClassSeats); | |
System.out.println(); | |
System.out.print("Please select an available seat to upgrade: "); | |
String newSeat = u_input.next(); | |
String[] seatLabel = seatLabelParts(newSeat); | |
if(belongsToFirstClass(newSeat)) { | |
if(swapSeat(seatLabel, foundPassenger)) { | |
System.out.printf( | |
"Upgrade successful.\n\n" + | |
"%s %s is currently sitting in %s\n\n", | |
firstname, lastname, seatLabel[0]+seatLabel[1].toUpperCase() | |
); | |
changesMadeToFile = true; | |
return; | |
} | |
System.out.println("\nThe seat you chose to upgrade to has already been reserved.\n"); | |
return; | |
} else { | |
System.out.println("\nThe seat you chose is not available in the first class\n"); | |
return; | |
} | |
} else { | |
//no passenger to upgrade | |
} | |
} | |
private static boolean belongsToFirstClass(String newSeat) { | |
String[] s = seatLabelParts(newSeat); | |
int row = convertToInt(s[0]); | |
if(row >= 1 && row <= 5) | |
return true; | |
return false; | |
} | |
private static void checkNoFlyList(String[][] noFly) { | |
boolean terroristFound = false; | |
if(noFly[0][0] == null) { | |
try { | |
Scanner noFlyReader = new Scanner(new File(parent + "noFly.csv")); | |
noFlyReader.nextLine(); | |
int index = 0; | |
while(noFlyReader.hasNextLine()) { | |
noFly[index] = noFlyReader.nextLine().split(","); | |
index++; | |
} | |
} catch (FileNotFoundException e) { | |
System.out.println("\nNo no-fly list included in the system.\n"); | |
return; | |
} | |
} | |
System.out.println(); | |
for(String[] terrorist : noFly) { | |
for(String[] passenger : seats) { | |
if(terrorist[0].equalsIgnoreCase(passenger[2]) && terrorist[1].equalsIgnoreCase(passenger[3])) { | |
System.out.printf( | |
"%s %s (seat: %s) is on the \"no fly\" list.\n", | |
passenger[2], passenger[3], passenger[0]+passenger[1].toUpperCase() | |
); | |
terroristFound = true; | |
} | |
} | |
} | |
System.out.println(); | |
if(!terroristFound) { | |
System.out.println("None of the passengers aboard this flight is on the no fly list.\n"); | |
} | |
return; | |
} | |
private static boolean tryAgain() { | |
System.out.print("Would you like to perform another transaction (yes/no)? "); | |
if(!isAnswer("yes", sc.next())) { | |
if(changesMadeToFile) | |
saveToFile(destination); | |
System.out.println("\nThank you for using Airline Reservation System! Good bye!"); | |
return false; | |
} | |
System.out.println(); //create a blank line between consecutive transactions | |
return true; | |
} | |
private static void getTicketPrices() throws IOException { | |
Scanner tickets = new Scanner(new File(parent+"ticketPrices.csv")); | |
tickets.nextLine(); //read away the headers | |
String[] prices = tickets.nextLine().split(","); | |
for (int i = 0; i < 2; i++) { | |
ticketPrices[i] = Double.valueOf(prices[i]); | |
} | |
tickets.close(); | |
} | |
private static Object getRouteName() { | |
String routeName = null; | |
switch(destination) { | |
case "kumasi": | |
routeName = "KUM"; | |
break; | |
case "tamale": | |
routeName = "TAM"; | |
break; | |
case "takoradi": | |
routeName = "TAK"; | |
break; | |
} | |
return routeName; | |
} | |
private static void changeSeatAssignment() { | |
//change the seat reservation of a customer. Customers can only move to | |
//empty seats in their classes | |
Scanner u_input = new Scanner(System.in); | |
System.out.print("Please enter your last name: "); | |
String[] foundPassenger = findPassengerByLastName(u_input.nextLine()); | |
if(foundPassenger != null) { | |
String[] emptySeats = getClassEmptySeats(foundPassenger[7]); | |
if(emptySeats != null) { | |
System.out.printf("\n" + | |
"Hello, %s %s - you are seated in %s in %s class.\n\n" + | |
"Here is the list of available %s seats:\n\n", | |
foundPassenger[2], foundPassenger[3], foundPassenger[0]+foundPassenger[1].toUpperCase(), | |
foundPassenger[7], foundPassenger[7] | |
); | |
displaySeats(emptySeats); | |
System.out.println(); | |
System.out.print("Please enter the seat number you wish to move to: "); | |
String[] seat = seatLabelParts(u_input.nextLine()); | |
if(swapSeat(seat, foundPassenger)) { | |
System.out.printf( | |
"Seat change successful.\n\n" + | |
"You are now seated in %s.", seat[0]+seat[1].toUpperCase() | |
); | |
System.out.println("\nYou have successfully changed your seat.\n"); | |
changesMadeToFile = true; | |
} else { | |
System.out.println("\nYour seat change could not be carried out successfully.\n"); | |
} | |
} else { | |
//there are no empty seats for the user to move into | |
System.out.println("\nAll the seats in your compartment/class have been reserved.\n"); | |
} | |
} else { | |
System.out.println("\nPassenger not found\n"); | |
// return; | |
} | |
} | |
private static void displaySeats(String[] emptySeats) { | |
for(String s : emptySeats) { | |
int labelSize = s.length()-1; | |
String seatLetter = s.substring(labelSize); | |
int row = convertToInt(s.substring(0, labelSize)); | |
String position = (seatLetter.equals("A") || seatLetter.equals("D")) ? "window" : "aisle"; | |
System.out.printf("%s (%s)", s, position); | |
System.out.printf((row >= 10 && row <= 13) ? " - emergency exit\n" : "\n"); | |
} | |
} | |
private static boolean seatReallyEmpty(String[] seat) { | |
int stop = convertToInt(seat[0]) * 4 - 1; | |
for (int i = stop - 3; i < stop; i++) { | |
if(seats[i][1].equals(seat[1]) && isEmpty(seats[i])) { | |
return true; | |
} | |
} | |
return false; | |
} | |
private static boolean swapSeat(String[] seat, String[] foundPassenger) { | |
if(convertToInt(foundPassenger[4]) < 16 && (convertToInt(seat[0]) >= 10 && convertToInt(seat[0]) <= 13)) { | |
return false; | |
} | |
if(seatReallyEmpty(seat)) { | |
if(reserveSeat(seat, foundPassenger[2], foundPassenger[3], convertToInt(foundPassenger[4]))) { | |
return reserveSeat(foundPassenger, "empty", "empty", 0); | |
} | |
} | |
return false; | |
} | |
private static int convertToInt(String string) { | |
return Integer.valueOf(string); | |
} | |
private static String[] seatLabelParts(String seatLabel) { | |
int length = seatLabel.length()-1; | |
return new String[] { seatLabel.substring(0, length), seatLabel.substring(length) }; | |
} | |
private static String[] getClassEmptySeats(String seatClass) { | |
StringBuilder emptySeats = new StringBuilder(); | |
int index = seatClass.equalsIgnoreCase("first") ? 0 : 20; | |
int stop = seatClass.equalsIgnoreCase("first") ? 20 : 70; | |
for (int i = index; i < stop; i++) { | |
if(isEmpty(seats[i])) { | |
emptySeats.append(seats[i][0]+seats[i][1].toUpperCase()+","); | |
} | |
} | |
return emptySeats.length() > 0 ? emptySeats.toString().split(",") : null; | |
} | |
/** | |
* | |
* @param String[][] | |
* @throws IOException | |
* | |
* This method reads a CSV extension file from the file system, splits the elements on | |
* the commas and put each line into different arrays of size 4. | |
* | |
* @return void | |
*/ | |
private static void populateFlightDatabase(String destination, String[][] seats) throws IOException { | |
openReadFile(String.format("%s%sList.csv", parent, destination), seats); | |
} | |
private static String customerMenu() { | |
System.out.print( | |
"\n1 - Check seat availability\n" + | |
"2 - Make a reservation\n" + | |
"3 - Print a boarding pass\n" + | |
"4 - Print a receipt\n" + | |
"5 - Change seat assignment\n\n" + | |
"Please enter your choice: " | |
); | |
return sc.next(); | |
} | |
private static String agentMenu() { | |
System.out.println("\nWelcome, agent! What would you like to do today?\n"); | |
System.out.printf( | |
"1 - Check \"no fly\" list\n" + | |
"2 - Perform upgrade\n" + | |
"3 - Print passenger roster\n" + | |
"4 - Print sales report\n\n" + | |
"Please enter your choice: " | |
); | |
return sc.next(); | |
} | |
private static void printAvailableSeats(String[][] seats) { | |
StringBuilder emptySeats = new StringBuilder(); | |
for (int i = 0; i < seats.length; i++) { | |
try { | |
if(isEmpty(seats[i])) { | |
emptySeats.append(String.format("%s - %s - %s%n", | |
getSeatLabel(seats[i]), getTicketClass(seats[i]), getSeatPosition(seats[i]) | |
)); | |
} | |
} catch (NullPointerException e) { | |
continue; | |
} | |
} | |
System.out.println(emptySeats); | |
} | |
private static void makeReservation(String[][] seats) { | |
Scanner input = new Scanner(System.in); | |
try { | |
String emptySeats = emptySeatsAvailable(seats); | |
String[] empty = emptySeats.split(","); | |
int firstClassAisleSeats = 0; | |
int firstClassWindowSeats = 0; | |
int economyClassAisleSeats = 0; | |
int economyClassWindowSeats = 0; | |
//emergency seats | |
int emergencyAisleSeats = 0; | |
int emergencyWindowSeats = 0; | |
int economyClassEmergencySeats = 0; | |
for (String seat : empty) { | |
int seatClass = convertToInt(seat.substring(0, seat.length()-1)); | |
String seatPosition = seat.substring(seat.length()-1); | |
if(seatClass > 0 && seatClass <= 5) { | |
if(seatPosition.equalsIgnoreCase("a") || seatPosition.equalsIgnoreCase("d")) { | |
firstClassWindowSeats++; | |
continue; | |
} | |
firstClassAisleSeats++; | |
} else if(seatClass > 5 && seatClass <= 18) { | |
if(seatClass >= 10 && seatClass <= 13) { | |
if(seatPosition.equalsIgnoreCase("a") || seatPosition.equalsIgnoreCase("d")) { | |
emergencyWindowSeats++; | |
} else if(seatPosition.equalsIgnoreCase("b") || seatPosition.equalsIgnoreCase("c")) { | |
emergencyAisleSeats++; | |
} | |
economyClassEmergencySeats++; | |
} | |
if(seatPosition.equalsIgnoreCase("a") || seatPosition.equalsIgnoreCase("d")) { | |
economyClassWindowSeats++; | |
continue; | |
} | |
economyClassAisleSeats++; | |
} else { | |
} | |
} | |
//get the total of first class seats available as well as economy seats | |
int firstClassSeats = firstClassAisleSeats + firstClassWindowSeats; | |
int economyClassSeats = economyClassAisleSeats + economyClassWindowSeats; | |
boolean exitFlag = false; | |
System.out.print("What is your first name? "); | |
firstname = input.nextLine(); | |
System.out.print("What is your last name? "); | |
lastname = input.nextLine(); | |
//if there's already a reserved seat with these first and last names, inform and exit | |
if(nameAlreadyExists()) { | |
System.out.println("\nPassengers with the same first and last names cannot join the same flight.\n" + | |
"A passenger has already booked with the same name as yours.\n"); | |
// if(changesMadeToFile) { saveToFile(destination); } | |
// System.exit(0); | |
return; | |
} | |
System.out.print("What is your age? "); | |
age = sc.nextInt(); | |
sc.nextLine(); //clear input from the Scanner object | |
String ticketClass = getTicketClass(economyClassSeats, firstClassSeats); | |
String seatPosition = null; | |
//String[] seat = null; | |
//boolean emergencyExit = emergencyExitSeatReserved(); | |
if(isAnswer("economy", ticketClass)) { | |
exitFlag = getEmergencyExitFlag(economyClassEmergencySeats, age); | |
seatPosition = exitFlag ? getSeatPosition(emergencyAisleSeats, emergencyWindowSeats) : | |
getSeatPosition(economyClassAisleSeats, economyClassWindowSeats); | |
if(seatPosition == null) { return; } | |
seat = getEconomyClassSeat(seats, exitFlag, seatPosition); | |
} else if(isAnswer("first class", ticketClass)) { | |
seatPosition = getSeatPosition(firstClassAisleSeats, firstClassWindowSeats); | |
if(seatPosition == null) { return; } | |
seat = getFirstClassSeat(seats, seatPosition); | |
} else { | |
//when customer's choice is neither economy or first class, throw an InputMismatchException | |
//and exit, without error message. | |
throw new InputMismatchException(); | |
} | |
//reserve a seat for this customer | |
if(reserveSeat(seat, firstname, lastname, age)) { | |
System.out.printf("Thank you %s %s! You are now booked in %s seat %s.\n", | |
capitalize(firstname), capitalize(lastname), seat[6], seat[0]+seat[1].toUpperCase()); | |
changesMadeToFile = true; | |
} | |
} catch (InputMismatchException e) { | |
//wrong input type submitted by user. for e.g. anything apart from an integer as age | |
System.out.println("\nYou have supplied wrong information. You may restart the process of reserving\n" + | |
"a seat on this flight or you may come back later. Thank you\n"); | |
sc.nextLine(); | |
} | |
} | |
private static boolean nameAlreadyExists() { | |
if(nameExists(lastname)) { | |
return true; | |
} | |
return false; | |
} | |
private static boolean nameExists(String name) { | |
for (int i = 0; i < seats.length; i++) { | |
if(seats[i][3].equalsIgnoreCase(name)) { | |
return true; | |
} | |
} | |
return false; | |
} | |
private static boolean reserveSeat(String[] s, String fN, String lN, int a) { | |
String age = Integer.toString(a); | |
int stop = (convertToInt(s[0]) * 4) - 1; | |
for (int i = stop-3; i < seats.length; i++) { | |
if(seats[i][1].equals(s[1])) { | |
seats[i][2] = fN.equalsIgnoreCase("empty") ? "empty" : capitalize(fN); | |
seats[i][3] = lN.equalsIgnoreCase("empty") ? "empty" : capitalize(lN); | |
seats[i][4] = age; | |
return true; | |
} | |
} | |
return false; | |
} | |
private static boolean getEmergencyExitFlag(int economyClassEmergencySeats, int age) { | |
String exit = null; | |
if(economyClassEmergencySeats > 0 && age >= 16) { | |
//there are seats in the economy class and in the emergency exit row too. | |
//btw, the emergency exit row seats are in the economy class. the customer is 16 or above | |
System.out.print("Would you like an emergency exit row seat? "); | |
exit = sc.next(); | |
} else if(age >= 16) { | |
//there are seats available in the economy class. but all seats in emergency | |
//exit rows have been reserved. | |
System.out.println("\nAll seats in the emergency exit rows have been reserved.\n"); | |
} else { | |
//even if there are seats in the emergency exit row, the customer is too young (less than 16) | |
//to sit in an emergency exit seat | |
System.out.println("\nPerson below age 16 are not allowed to sit in emergency seat.\n"); | |
} | |
return isAnswer("yes", exit); | |
} | |
private static String getSeatPosition(int aisle, int window) { | |
if(aisle > 0 && window > 0) { | |
System.out.print("What is your seat type preference (aisle or window)? "); | |
String response = sc.next(); | |
if(isAnswer("window", response)) { | |
return "window"; | |
} else if(isAnswer("aisle", response)) { | |
return "aisle"; | |
} else { | |
System.out.println("\nNo such seat.\n"); | |
return null; | |
} | |
} else if(aisle > 0) { | |
System.out.print("\nAll window seats have been reserved.\nWould you like a seat by the aisle? "); | |
if(isAnswer("yes", sc.next())) { return "aisle"; } | |
else { | |
System.out.print("\nWould you like any other seat in the non-emergency rows of the economy class? "); | |
if(isAnswer("yes", sc.next())) { | |
//offer other seats in the economy class | |
} | |
else { | |
System.out.println("\nThank you for using Airline Reservation System! Good bye!"); | |
System.exit(0); | |
} | |
} | |
} else if(window > 0) { | |
System.out.print("\nAll aisle seats have been reserved.\nwould you like a seat by the window? "); | |
if(isAnswer("yes", sc.next())) { return "window"; } | |
else { | |
if(!tryAgain()) { | |
System.exit(0); | |
} | |
} | |
} | |
return null; | |
} | |
private static String getTicketClass(int economyClassSeats, int firstClassSeats) { | |
String ticketClass = null; | |
if(economyClassSeats > 0 && firstClassSeats > 0) { | |
System.out.print("Would you like a first class or economy class seat? "); | |
ticketClass = sc.nextLine(); | |
} else if(economyClassSeats > 0) { | |
System.out.print("All seats in the first class have been reserved." + | |
"\nWould you like an economy class seat? "); | |
if(isAnswer("yes", sc.next())) { | |
ticketClass = "economy"; | |
} | |
} else if(firstClassSeats > 0) { | |
System.out.print("All seats in the economy class class have been reserved." + | |
"\nWould you like a first class seat? "); | |
if(isAnswer("yes", sc.next())) { | |
ticketClass = "first class"; | |
} | |
} | |
return ticketClass; | |
} | |
private static void printReceipt() { | |
try { | |
System.out.print("Please enter the number of passengers on the receipt: "); | |
int numberOfPassengers = sc.nextInt(); | |
sc.nextLine(); | |
StringBuilder receipt = new StringBuilder(); | |
if(numberOfPassengers > 0) { | |
for (int i = 0; i < numberOfPassengers; i++) { | |
System.out.print("Please enter the last name of a passenger: "); | |
String lastname = sc.nextLine(); | |
String passengerReceipt = receiptOf(lastname); | |
if(passengerReceipt == null) { | |
throw new Exception(); | |
} | |
receipt.append(passengerReceipt); | |
} | |
} else { | |
System.out.printf("\nInvalid number of passengers specified [%s].\n" + | |
"Receipts cannot be printed. Thank you\n", String.valueOf(numberOfPassengers)); | |
return; | |
} | |
System.out.println("-------------------------------------"); | |
System.out.println(receipt); | |
System.out.printf("Total: %.0f GHc\n", total); | |
System.out.println("-------------------------------------\n"); | |
total = 0.0; //reset total to 0 | |
} catch(InputMismatchException e) { | |
System.out.println("\nAn integer was expected.\n\n"); | |
sc.nextLine(); | |
} catch(Exception ex) { } | |
} | |
private static String receiptOf(String lastname) { | |
String[] passenger = findPassengerByLastName(lastname); | |
if(passenger == null) { | |
System.out.println("\nNo such passenger(s) on this flight.\n"); | |
return null; | |
} | |
double ticketPrice = passenger[7].equalsIgnoreCase("economy") ? ticketPrices[0] : ticketPrices[1]; | |
total += ticketPrice; | |
return String.format( | |
"Name: %s %s\n" + | |
"Departure Date: XX/XX/XXXX\n" + | |
"Destination: ACC to %s\n" + | |
"Class: %s\n" + | |
"Ticket Price: %.1f GHc\n\n", | |
capitalize(passenger[2]), capitalize(passenger[3]), getRouteName(), capitalize(passenger[7]), | |
ticketPrice | |
); | |
} | |
private static void printBoardingPass() { | |
System.out.print("Please enter your last name: "); | |
String lastName = sc.next(); | |
String[] passenger = findPassengerByLastName(lastName); | |
if(passenger != null) { | |
System.out.println(); | |
System.out.printf( | |
"Here is your boarding pass:\n\n" + | |
"----------------------------------\n" + | |
"Name: %s %s\n" + | |
"Depature Date: XX/XX/XXXX\n" + | |
"Destination: ACC to %s\n" + | |
"Class: %s\n" + | |
"Seat: %s\n" + | |
"----------------------------------\n\n", | |
capitalize(passenger[2]), capitalize(passenger[3]), getRouteName(), capitalize(passenger[7]), | |
passenger[0]+passenger[1].toUpperCase() | |
); | |
} else { | |
System.out.println("Sorry, there is not such passenger booked for this flight.\n"); | |
} | |
} | |
private static String[] findPassengerByLastName(String lastname) { | |
for(String[] passenger : seats) { | |
if(passenger[3].equalsIgnoreCase(lastname)) { | |
return passenger; | |
} | |
} | |
return null; | |
} | |
private static String getRoute(String clientType) throws Exception { | |
String client = null; | |
if(isAnswer("customer", clientType)) { client = "customer"; } | |
else if(isAnswer("gate agent", clientType) || isAnswer("agent", clientType)) { | |
client = "agent"; | |
} | |
else { | |
System.out.println("\nYou should be either a customer or a gate agent to use this system.\n"); | |
throw new Exception(); | |
} | |
System.out.printf("\nWelcome, %s! which flight would you like to use?\n\n" + | |
"1 - ACC to TAK\n" + | |
"2 - ACC to TAM\n" + | |
"3 - ACC to KUM\n\n" + | |
"Please enter your choice: ", client); | |
String destination = null; | |
switch(sc.nextInt()) { | |
case 1: | |
destination = "takoradi"; | |
break; | |
case 2: | |
destination = "tamale"; | |
break; | |
case 3: | |
destination = "kumasi"; | |
break; | |
} | |
if(destination == null) { | |
throw new InputMismatchException(); | |
} | |
return destination; | |
} | |
private static void openReadFile(String path, String[][] seats) throws IOException { | |
try { | |
//set to read from the file... | |
Scanner reservationsFileReader = new Scanner(new File(path)); | |
int index = 0; //indexer for first class section | |
//read away the headers for the csv document | |
reservationsFileReader.nextLine(); | |
//fill the seats with reservation information in the file | |
while(reservationsFileReader.hasNextLine()) { | |
String[] passenger = reservationsFileReader.nextLine().split(","); | |
int compartmentNumber = convertToInt(passenger[0]); | |
if(compartmentNumber > 0 && compartmentNumber <= 18) { | |
//shovel them into the first class section | |
seats[index] = passenger; | |
index++; | |
} else { | |
continue; //ignore passengers for sections that are not available on this flight | |
} | |
} | |
reservationsFileReader.close(); | |
} catch (FileNotFoundException e) { | |
//in case records cannot be read from a file, exit | |
System.out.println("\nSorry but this flight is not ready yet for booking. Thank you."); | |
System.err.println("error reading database of reservations already made. check /path/to/file.csv"); | |
System.exit(1); | |
} | |
} | |
private static String getSeatLabel(String[] seat) { | |
return seat[0] + seat[1]; | |
} | |
private static String getTicketClass(String[] seat) { | |
return seat[7]; | |
} | |
private static String getSeatPosition(String[] seat) { | |
return seat[6]; | |
} | |
private static String emptySeatsAvailable(String[][] seats) { | |
StringBuilder emptySeats = new StringBuilder(); | |
for (int i = 0; i < seats.length; i++) { | |
try { | |
if(isEmpty(seats[i])) { | |
emptySeats.append(String.format("%s,", seats[i][0]+seats[i][1])); | |
} | |
} catch (NullPointerException e) { | |
continue; | |
} | |
} | |
return emptySeats.toString(); | |
} | |
private static boolean isAnswer(String requiredAnswer, String suppliedAnswer) { | |
try { | |
return requiredAnswer.substring(0, suppliedAnswer.length()).equalsIgnoreCase(suppliedAnswer); | |
} catch(Exception e) { return false; } | |
} | |
private static String[] getFirstClassSeat(String[][] seats, String position) { | |
String[] foundSeat = null; | |
for (int i = 0; i < 20; i++) { | |
if(isEmpty(seats[i])) { | |
foundSeat = getSeat(seats, position, "window", "aisle", i); | |
if(foundSeat != null) { break; } | |
} | |
} | |
return foundSeat; | |
} | |
private static String[] getEconomyClassSeat(String[][] seats, boolean emergency, String position) { | |
return getClassSeat(20, seats.length, seats, emergency, position); | |
} | |
private static String[] getClassSeat(int start, int stop, String[][] seats, boolean emergency, String position) { | |
String[] foundSeat = null; | |
for (int i = start; i < stop; i++) { | |
if(isEmpty(seats[i])) { | |
if(emergency) { | |
if(Boolean.valueOf(seats[i][5])) { | |
foundSeat = getSeat(seats, position, "window", "aisle", i); | |
if(foundSeat != null) { break; } | |
} | |
} else { | |
if(!Boolean.valueOf(seats[i][5])) { | |
foundSeat = getSeat(seats, position, "window", "aisle", i); | |
if(foundSeat != null) { break; } | |
} | |
} | |
} | |
} | |
return foundSeat; | |
} | |
private static String[] getSeat(String[][] seats, String position, String window, String aisle, int i) { | |
if(position.equals(window) && (seats[i][1].equals("a") || seats[i][1].equals("d"))) { | |
return new String[] { seats[i][0], seats[i][1] }; | |
} else if(position.equals(aisle) && (seats[i][1].equals("b") || seats[i][1].equals("c"))) { | |
return new String[] { seats[i][0], seats[i][1] }; | |
} | |
return null; | |
} | |
private static boolean isEmpty(String[] seat) { | |
//returns true if the given row in the 2-dimensional array has "empty" in both columns 3 and 4 | |
return seat[2].equalsIgnoreCase("empty") && seat[3].equalsIgnoreCase("empty"); | |
} | |
private static void saveToFile(String path) { | |
try { | |
FileWriter destinationFile = new FileWriter( | |
String.format("src/airlinereservationsystem_yawboakyeyiadom/files/%sList.csv", path) | |
); | |
destinationFile.write("row,seat,first,last,age,exit row flag,seat position,ticket class\r\n"); | |
for(String[] passenger : seats) { | |
for (int i = 0; i < 8; i++) { | |
if (i == 7) { destinationFile.write(String.format("%s", passenger[i])); continue; } | |
destinationFile.write(String.format("%s,", passenger[i])); | |
} | |
destinationFile.write("\r\n"); | |
} | |
destinationFile.flush(); | |
destinationFile.close(); | |
} catch(IOException e) { | |
} | |
} | |
private static String capitalize(String string) { | |
//capitalize only the first letter of the string | |
return Character.toUpperCase(string.charAt(0)) + string.substring(1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment