Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Q2: Add functionality to search for an Itinerary. Create labels and text fields that allow the user to enter a bus type, a source bus

Q2: Add functionality to search for an Itinerary.

Create labels and text fields that allow the user to enter a bus type, a source bus station, and a destination bus station, as well as the departure time and the arrival time to search for one or more available bus routes in an Itinerary. Also, create a ComboBox (see Chapter 11) that will allow the user to select from a list of bus route Itineraries. Each item in the ComboBox represents an Itinerary element, e.g. the first comboBox element is the first Itinerary in the array. [15 pts]

Methods:

Your BusFrame class should include the following methods (The methods that check for validation must have message dialogs indicating to the user if the information entered in each text field is invalid):

initComponents() : Method used to initialize UI components and controls

default constructor : Inside the default constructor, call the initComponents() method

convertTime(String input) : converts time string (from text input -- ie departure time text field) to a Time object and returns the Time object

checkValidBusType() : returns true if entered bus type is valid and exists in BusType enum and can be converted to a BusType object

checkValidBusStations(String src, String dest) : will return true if both the source and destination bus stations entered in the text fields exist in BusStation enum

checkValidTime(String depTime, String arriveTime) : checks if the time is in valid format (hh:mm a) and returns true if it is in the correct format

Make sure all text fields have error checking and exception handling for invalid input. For example, if the user enters an integer as a departure time instead of a String (ie 1200 instead of 12:00 PM), a JOptionPane error message should appear stating, "Incorrect format for departure time." If the bus type they entered is not in the BusType enum, then the option pane should say, "Bus type unavailable. Please choose a different bus type." If the bus station they entered is not in the BusStation enum, then the option pane should say, "Unknown city." Make sure the times are in hh:mm a format. [8 pts]

All files below

File 1 Bus.java

/** * Bus class. * @author Sylvia Barnai */

public class Bus {

BusType busType; //String model;

public Bus(BusType busType/*, String model*/) { this.busType = busType; //this.model = model; }

public BusType getBusType() { return this.busType; }

/*public String getModel() { return this.model; }*/

@Override public String toString() { return this.busType + " * "/* + this.model*/; }

public String toStringWithNumber(String routeNumber) { return this.busType + " " + routeNumber + " * "/* + this.model*/; } }

File 2 - BusRoute.java

/** * BusRoute class. * @ Sylvia Barnai **/ import java.text.NumberFormat;

public class BusRoute { Bus bus; String routeNumber; double routeCost; Time departureTime; int durationTime; BusStation sourceBusStation; BusStation destinationBusStation;

public BusRoute(Bus bus, String routeNumber, double routeCost, Time departureTime, int durationTime, BusStation sourceBusStation, BusStation destinationBusStation) { this.bus = bus; this.routeNumber = routeNumber; this.routeCost = routeCost; this.departureTime = departureTime; this.durationTime = durationTime; this.sourceBusStation = sourceBusStation; this.destinationBusStation = destinationBusStation; }

public Bus getBus() { return bus; }

public String getNumber() { return routeNumber; }

public double getCost() { return routeCost; }

public BusStation getDestination() { return destinationBusStation; }

public Time getDeparture() { return departureTime; }

public Time getArrival() { Time arrivalTime = new Time(departureTime.getHour(), departureTime.getMinute()); arrivalTime.addMinutes(durationTime); return arrivalTime; }

public BusStation getSource() { return sourceBusStation; }

public String toOverviewString() { NumberFormat nf = NumberFormat.getCurrencyInstance(); String output = nf.format(routeCost) + " " + getDeparture() + " - "; output += getArrival() + "\t" + durationTime / 60 + "h:" + durationTime % 60 + "m"; output += " " + bus.getBusType() + "\t\t" + sourceBusStation + "-" + destinationBusStation; return output; }

public String toDetailedString() { String output = getDeparture() + " - " + getArrival() + " " + BusStation.getBusStationCity(sourceBusStation) + " (" + sourceBusStation + ") - " + BusStation.getBusStationCity(destinationBusStation) + " (" + destinationBusStation + ")" + " " + bus.getBusType() + " " + routeNumber /* + " * " + bus.getModel()*/; return output;

}

}

File 3 - BusStation.java

/** * The BusStation class. * @author Sylvia Barnai */

public enum BusStation { PHX, LAX, LVS, SAN, SFO, YUM;

public static String getBusStationCity(BusStation busStation) {

switch (busStation) { case PHX: return "Phoenix"; case LAX: return "Los Angeles";

case LVS: return "Las Vegas"; case SAN: return "San Diego";

case SFO: return "San Fransisco";

default: return "Unknown City";

} }

}

File 4 - BusType

/** * * BusType class * @author Sylvia Barnai */

public enum BusType { Greyhound, BoltBus, Megabus; }

File 5 - Itenerary.java

/* * * Itinerary class * @author Sylvia Barnai */

import java.text.NumberFormat;

public class Itinerary { private BusRoute b1; private BusRoute b2;

public Itinerary(BusRoute first) { b1 = first; b2 = null; }

public Itinerary(BusRoute first, BusRoute second) { b1 = first; b2 = second; }

public BusRoute getFirstBusRoute() { return b1; }

public BusRoute getSecondBusRoute() { return b2; }

public boolean hasConnection() { if(b2 == null) return false; else return true; }

public double getTotalCost() { double total = 0;

if(b2 != null) total = b1.getCost() + b2.getCost(); else total = b1.getCost();

return total; }

public Time getDeparture() { return b1.getDeparture(); }

public Time getArrival() { return b2.getArrival(); }

public String toString() { String str = ""; NumberFormat fmt1 = NumberFormat.getCurrencyInstance(); str += "Total cost: " + fmt1.format(getTotalCost()) + " "; str += b1.toDetailedString(); if(b2 != null) str += " " +b2.toDetailedString();

return str; } }

File 6 - RouteManager.java

/* * * Route Manager class * @author Sylvia Barnai */

import java.util.Arrays;

public class RouteManager { private BusRoute[] busRoutes; private int busRouteCount;

public RouteManager() { busRoutes = new BusRoute[1]; busRouteCount = 0; }

public void addBusRoute(BusRoute newTrainRoute) { busRouteCount++; if (busRoutes.length == busRouteCount) { increaseSize(); } busRoutes[busRouteCount-1] = newTrainRoute; }

private void increaseSize() {

BusRoute[] temp = new BusRoute[busRoutes.length * 2]; for (int i = 0; i < busRouteCount; i++) { temp[i] = busRoutes[i]; }

busRoutes = temp; }

public Itinerary[] findItineraries(BusStation src, BusStation dest, Time idealDeparture) {

Itinerary[] busRouteMatches = new Itinerary[100]; searchOneBusRouteItinerary(src, dest, idealDeparture, busRouteMatches); return shrinkItineraries(busRouteMatches); } private void searchOneBusRouteItinerary(BusStation src, BusStation dst, Time depart, Itinerary[] itineraryArray) { int i = 0; boolean timeComparison; for (int j = 0; j < busRouteCount; j++) { timeComparison = compareTimes(depart, busRoutes[j].getDeparture()); if (busRoutes[j].getSource() == src && timeComparison) { if (busRoutes[j].getDestination() == dst) { itineraryArray[i] = new Itinerary(busRoutes[j]); i++; } else { i = searchTwoBusRoutesItinerary(busRoutes[j], dst, itineraryArray, i); } } } } private int searchTwoBusRoutesItinerary(BusRoute primaryBusRoute, BusStation dst, Itinerary[] itineraryArray, int busRoutesIndex) { boolean timeComparison; for (int k = 0; k < busRouteCount; k++) { Time newArrival = primaryBusRoute.getArrival().getCopy(); newArrival.addMinutes(10); timeComparison = compareTimes(newArrival, busRoutes[k].getDeparture()); if (primaryBusRoute.getDestination() == busRoutes[k].getSource() && busRoutes[k].getDestination() == dst && timeComparison) { itineraryArray[busRoutesIndex] = new Itinerary(primaryBusRoute, busRoutes[k]); busRoutesIndex++; } } return busRoutesIndex; } private boolean compareTimes(Time time1, Time time2) { if (time1.getHour() > time2.getHour()) { return false; } else if (time1.getMinute() > time2.getMinute()) { return false; } else { return true; } } private Itinerary[] shrinkItineraries(Itinerary[] itineraries) { int newSize = 0; for (int i = 0; i < itineraries.length; i++) { if (itineraries[i] != null) { newSize++; } }

Itinerary[] newItinerary = new Itinerary[newSize]; int newIndex = 0; for (int i = 0; i < itineraries.length; i++) { if (itineraries[i] != null) { newItinerary[newIndex] = itineraries[i]; newIndex++; } }

return newItinerary; } }

File 7 - Time.java

/** * Time class * @author Sylvia Barnai */

public class Time {

int hour; int minute;

public Time(int hour, int minute) { this.hour = hour; this.minute = minute; }

public Time() { this.hour = 12; this.minute = 0; }

public int getHour() { return this.hour; }

public int getMinute() { return this.minute; }

public void addHours(int hoursToAdd) { this.hour = ((this.hour + hoursToAdd % 24) + 24) % 24; }

public void addMinutes(int minutesToAdd) { this.minute += minutesToAdd; this.minute = ((this.minute % (24*60)) + (24*60)) % (24*60); this.addHours((int) Math.floor(((double)this.minute)/(60.0))); this.minute = this.minute % 60; }

public void addTime(Time timeToAdd) { this.addHours(timeToAdd.hour); this.addMinutes(timeToAdd.minute); }

public Time getCopy() { return new Time(this.hour, this.minute); }

public boolean isEarlierThan(Time timeToCompare) { if (hour < timeToCompare.getHour()) { return true; } else { return false; } }

public boolean isSameTime(Time timeToCompare) { if ((this.hour==timeToCompare.hour) && (this.minute==timeToCompare.minute)) { return true; } else { return false; } }

public boolean isLaterThan(Time timeToCompare) { if (hour > timeToCompare.getHour()) { return true; } else { return false; } } private String formatDigits(int i) { boolean negative = false; if (i < 0) negative = true; int positiveMinutes = Math.abs(i); int hours = (int) Math.floor(((double)positiveMinutes)/(60.0)); int minutes = positiveMinutes % 60; String hourMinuteString = hours + "h:" + minutes + "m"; if (negative) { hourMinuteString = "-(" + hourMinuteString + ")"; } return hourMinuteString; }

@Override public String toString() { int twelveHour = ((this.hour-1) % 12 + 12) % 12 + 1; String minuteString = String.format("%02d",this.minute); String meridiem; if (this.hour<=11) { meridiem = "AM"; } else { meridiem = "PM"; } return twelveHour + ":" + minuteString + meridiem; } }

File 8 - ItineraryTest.java

/** * Do not submit this file! It is only for testing. The tests here are not * comprehensive, you should consider if any others are needed. */ public class ItineraryTest { public static void main(String[] args) { BusRoute b1 = new BusRoute(new Bus(BusType.Greyhound), "135", 75, new Time(8, 20), 440, BusStation.PHX, BusStation.SAN); BusRoute b2 = new BusRoute(new Bus(BusType.BoltBus), "201", 65, new Time(17, 50), 746, BusStation.SAN, BusStation.SFO); Itinerary i1 = new Itinerary(b1); Itinerary i2 = new Itinerary(b1, b2); System.out.println(i1); System.out.println(); System.out.println(i2); } }

File 9 - RouteManagerTest.java

/** * Do not submit this file! It is only for testing. The tests here are not * comprehensive, you should consider if any others are needed. */ public class RouteManagerTest {

RouteManager manager;

public static void main(String[] args) { RouteManagerTest rmt = new RouteManagerTest(); rmt.run(); }

public RouteManagerTest() { manager = new RouteManager(); loadBusRoutes(); }

public void run() { Itinerary[] itineraries = manager.findItineraries(BusStation.PHX, BusStation.SFO, new Time(8, 0));

for (Itinerary i : itineraries) { System.out.println(i); } }

private void loadBusRoutes() { manager.addBusRoute(new BusRoute(new Bus(BusType.Greyhound), "594", 45, new Time(10, 50), 230, BusStation.PHX, BusStation.YUM));

manager.addBusRoute(new BusRoute(new Bus(BusType.Megabus), "205", 46, new Time(11, 5), 360, BusStation.LAX, BusStation.LVS));

manager.addBusRoute(new BusRoute(new Bus(BusType.Greyhound), "135", 75, new Time(8, 20), 440, BusStation.PHX, BusStation.SAN));

manager.addBusRoute(new BusRoute(new Bus(BusType.BoltBus), "228", 50, new Time(7, 10), 192, BusStation.SAN, BusStation.LAX));

manager.addBusRoute(new BusRoute(new Bus(BusType.Megabus), "270", 50, new Time(12, 50), 445, BusStation.LAX, BusStation.SFO));

manager.addBusRoute(new BusRoute(new Bus(BusType.BoltBus), "201", 65, new Time(17, 50), 746, BusStation.SAN, BusStation.SFO)); } }

File I am currently working on - BusFrame.java

/* Base file for Unit 6/7 programming assignment. */

import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.*; import java.text.DateFormat; import java.text.SimpleDateFormat;

import java.util.Locale;

import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener;

public class BusFrame extends JFrame {

/* Declare your UI variables and other class level variables at the class level (outside of the main method). These include GUI controls, such as a panel, text fields, combo box, slider, labels, and buttons. */ private static final int FRAME_WIDTH = 475; private static final int FRAME_HEIGHT = 500; private JPanel panel1, sliderPanel; private JLabel colorChoiceLabel, busTypeLabel; private JLabel sourceStationLabel, destStationLabel; private JLabel arrivalLabel, departureLabel; private JComboBox busRouteCombo; private JSlider colorChoiceSlider; private ChangeListener listener; private Time time;

/* Place all of your UI initialization code inside the initComponents() method. Also, add UI components to the panel. (For example: panel = new JPanel(); ) */ public void initComponents() { panel1 = new JPanel(); panel1.setLayout(null); add(panel1); setSize(FRAME_WIDTH, FRAME_HEIGHT);

// Create listeners for each button/control and add action listeners to each UI control ActionListener comboListener = new ComboListener();

ActionListener viewListener = new ViewListener();

ActionListener searchListener = new SearchListener();

ChangeListener sliderListener = new SliderListener(); sliderPanel(); setPanelColor(); }

public BusFrame() { initComponents();

}

/** * Converts the time String to a Time object. Uncomment this method and * implement it * */ /* private Time convertTime() {

// Modify this method so that it returns the correct time Time time = new Time(hours, minutes); return time; } */ /** * SliderListener class that changes the color of the panel to a grayscale * color when the slider is moved * */ class SliderListener implements ChangeListener {

public void stateChanged(ChangeEvent event) { setPanelColor(); }

}

/** * ComboListener class used to get the selected option in the itineraries * combobox * */ class ComboListener implements ActionListener {

public void actionPerformed(ActionEvent event) {

}

}

/** * SearchListener class is used to populate the itineraries combobox * (validating text input is not required, but recommended) * */ class SearchListener implements ActionListener {

public void actionPerformed(ActionEvent event) {

}

}

/** * ViewListener class validates bus type, source and destination bus * stations, departure and arrival times, creates an instance of RouteFrame * and opens the route frame that shows the results of the bus route search * */ class ViewListener implements ActionListener {

public void actionPerformed(ActionEvent event) { } }

/** * Checks if the bus type entered in the bus type text field can be * converted to a busType object * * @return true if entered bus type is valid and exists in busType enum * */ private boolean checkValidBusType() {

return false; }

/** * Checks if source and destination bus stations entered in the text fields * exist in busStation enum * * @param src The entered source (departure) bus station * @param dest The entered destination bus station * @return true if they are both valid bus station * */ private boolean checkValidBusStations(String src, String dest) { return false;

}

/** * Checks if the time is in valid format (hh:mm a) * * @param depTime The departure time text field * @param arriveTime The arrival time text field * */ private boolean checkValidTime(String depTime, String arriveTime) {

return false; } //Creates the panel to holde the JSlider that changes the top panel color. public void sliderPanel() { colorChoiceSlider = new JSlider(0,255,255); colorChoiceSlider.addChangeListener(listener); colorChoiceSlider.setMajorTickSpacing(64); colorChoiceSlider.setPaintTicks(true); colorChoiceSlider.setPaintLabels(true); colorChoiceSlider.setSnapToTicks(true); colorChoiceLabel = new JLabel("Choose Color: "); sliderPanel = new JPanel(); sliderPanel.setLayout(new GridLayout(2, 1)); sliderPanel.add(colorChoiceLabel); colorChoiceLabel.setHorizontalAlignment(JLabel.CENTER); sliderPanel.add(colorChoiceSlider); add(sliderPanel, BorderLayout.SOUTH); } //Sets the color of the panel based on the position of the JSlider public void setPanelColor() { int colorNum = 255, colorNum2 = 255, colorNum3 = 255; String colorName = "Choose Color: "; if (colorChoiceSlider.getValue() == 255) { colorNum = 255; colorNum2 = 0; colorNum3 = 0; colorName = "Red"; colorChoiceLabel.setText("Choose Color: " + colorName); }

panel1.setBackground(new Color(colorNum, colorNum2, colorNum3)); panel1.repaint(); } // Initialize BusFrame and set its properties in the main method (size, whether it is resizable, title, default close operation, and visibility) public static void main(String[] args) { BusFrame frame = new BusFrame(); frame.setTitle("Bus Route Reservation"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

The World Wide Web And Databases International Workshop Webdb 98 Valencia Spain March 27 28 1998 Selected Papers Lncs 1590

Authors: Paolo Atzeni ,Alberto Mendelzon ,Giansalvatore Mecca

1st Edition

3540658904, 978-3540658900

More Books

Students also viewed these Databases questions