Java For this assignment you will re-implement the Air Ticket Redeemer, refer to
ID: 3869224 • Letter: J
Question
Java
For this assignment you will re-implement the Air Ticket Redeemer, refer to the output screen
The Destination class should remain the same as that developed in Assignment 4. This reusability is one of the advantages of encapsulation, i.e., using object-oriented methodology.
In addition, the MileRedeemer class from Assignment 4 can be reused as well. Many methods of MileRedeemer can be invoked directly by your application, such as readDestinations() and the method that contains the redemption algorithm. There should be no part of your application that displays console-type output as you did in Assignment 4.
where the arguments are in the range 0...255 and the higher the number, the lighter the color. Use colors that are not too intense and displeasing to a user, and be sure that the text is completely legible.
The left panel contains a JList so that the user can go back and forth to look at the information of different tickets to different cities. The array of strings returned by the MileRedeemer method getCityNames() can be used to populate the JList. When a city in the JList is selected, its details (i.e., the members of its corresponding Destination object) should be displayed in the corresponding JTextFields. These JTextFields are not editable. To listen for this event, implement the interface javax.swing.event.ListSelectionListener, and provide the method
public void valueChanged(ListSelectionEvent e)
Add a new method to your MileRedeemer class to return the corresponding Destination object for a given city name, e.g.:
public Destination findDestination(String cityName)
The right panel takes in the accumulated miles using a JTextField and a JSpinner. After the "Redeem Tickets" button is clicked, it outputs ticket details in a JTextArea, and the remaining miles in a JTextField. The components for output are not editable.
The Input File
Create a small GUI window to ask for the name of the input destinations file.
How to populate the month Strings for the JSpinner
The spinner's month Strings can be obtained using the following code. (Some logic is included to remove an extra, empty value.)
protected String[] getMonthStrings()
{
String[] months = new java.text.DateFormatSymbols().getMonths();
int lastIndex = months.length - 1;
if (months[lastIndex] == null || months[lastIndex].length() <= 0)
{
String[] monthStrings = new String[lastIndex];
System.arraycopy(months, 0, monthStrings, 0, lastIndex);
return monthStrings;
}
else
{
return months;
}
}
Other Hints
Do not use a form or GUI builder in your IDE to build your GUI; you must code it all by hand.
You are allowed to use GridBagLayout, about which more can be found here.
Any error messages or messages printed as a result of caught exceptions should be printed on the Java console.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
import java.util.Scanner; // This is for accepting user input.
import java.io.*; // This is for file input/output.
// Declaration of class MileRedemptionApp
public class MileRedemptionApp
{
// main - if file not found, throw an exception
public static void main(String[] args) throws FileNotFoundException
{
// Create a scanner object for file.
Scanner keyScan = new Scanner( System.in ) ;
// File paths
// File text = new File("C:/NIU_CSCI_470/archive/destination.txt");
// File text = new File("C:/learnJava/JavaAirlines/destination.txt");
// Prompt user to enter file name.
System.out.print("Please enter the name of the file: ");
// Accept the file.
String fileName = keyScan.next( );
// Create a new File object.
File text = new File(fileName);
// Create another Scanner object fileScan.
Scanner fileScan = new Scanner(text);
// Print a border and label that welcomes user to the application.
System.out.println("-------------------------------------------------");
System.out.println("WELCOME TO THE JAVA AIRLINES MILES REDEMPTION APP");
System.out.println("-------------------------------------------------");
System.out.println(" ");
// Show user what cities he/she can travel to.
System.out.println("List of destination cities you can travel to: ");
// Create a MileRedeemer object MR.
MileRedeemer MR = new MileRedeemer();
// Call method readDestinations, passing it fileScan.
MR.readDestinations(fileScan);
// Call method getCityNames and put cities into a String array.
String cities[] = MR.getCityNames();
System.out.println(" ");
// Print however many cities there are in the array cities.
for (int i = 0; i < cities.length; i++)
{
// Print cities.
System.out.println(cities[i]);
}
// If user answers yes
char answer = 'Y';
// Create a new Scanner object scMiles.
Scanner scMiles = new Scanner( System.in );
// Create a new Scanner object scAnswer.
Scanner scAnswer = new Scanner( System.in ) ;
// Create a new Scanner object scMonth.
Scanner scMonth = new Scanner( System.in );
do
{
System.out.println(" ");
// Prompt user for accumulated Frequent Flyer Miles.
System.out.print("Please enter your accumulated Frequent Flyer Miles: ");
// Accept miles.
int miles = scMiles.nextInt( );
System.out.println(" ");
// Prompt user to enter month of departure.
System.out.print("Please enter your month of departure (1-12): ");
// Accept month of departure.
int month = scMonth.nextInt( );
System.out.println(" ");
// Tell user what he/she can redeem with miles.
System.out.println("Your Frequent Flyer Miles can be used to redeem the following tickets:");
System.out.println(" ");
// Call method redeeMiles, passing it miles and month.
// Store results in array results.
String results[] = MR.redeemMiles(miles, month);
// Print the results of array results.
for (int i = 0; i < results.length; i++)
{
// If element is not null,
if (results[i] != null)
{
// print results[i].
System.out.println(results[i]);
}
}
// Call method redeemMiles, passing it miles and month.
MR.redeemMiles(miles, month);
System.out.println(" ");
// Show remaining Frequent Flyer Miles.
System.out.println("Your remaining Frequent Flyer Miles: " + MR.getRemainingMiles());
// Ask user if he/she would like to continue with application.
System.out.print("Do you want to continue (y/n)? ");
// Accept an answer of 'y' or 'n' for yes or no, respectively.
answer=scAnswer.next().charAt(0);
// The application will continue until the user decides to stop.
} while (answer != 'n');
// Close fileScan.
fileScan.close();
// Close keyScan.
keyScan.close();
// Close scAnswer.
scAnswer.close();
// Close scMiles.
scMiles.close();
// Close scMonth.
scMonth.close();
// Print a border and a label that thanks traveler for using the application.
System.out.println("------------------------------------------------------------");
System.out.println("THANK YOU FOR USING THE JAVA AIRLINES MILES REDEMPTION APP!");
System.out.println("------------------------------------------------------------");
}
}
import java.util.*;
// Declaration of class MileRedeemer.
public class MileRedeemer
{
// Create an ArrayList of type Destination called destinationList.
ArrayList<Destination> destinationList = new ArrayList<Destination>();
// Initialize remainingMiles to 0.
static int remainingMiles = 0;
/***************************************************************
readDestinations
Use: Read and parses the destination data into an array of
Destination objects, which should then be sorted by their normal
mileage.
Parameters: 1. fileScanner - a Scanner object that reads and parses
the destination data into an array of Destination objects.
Returns: Nothing.
Notes: A Scanner object is used as an input parameter here
for flexibility and reusability.
***************************************************************/
public void readDestinations(Scanner fileScanner)
{
// While there is data in the file, put each city and field on a line,
// separating them by the semicolon (";") delimiter.
while(fileScanner.hasNextLine())
{
String line = fileScanner.nextLine(); // Put the next line into line.
String[] splitedStr = line.split(";"); // Split fields by semicolon
// delimiter.
// Create a destination object dest and put each field in an array element.
Destination dest = new Destination (splitedStr[0], splitedStr[1], splitedStr[2], splitedStr[3], splitedStr[4]); //Create a new object.
// Call add passing it dest - Adding it to the list.
destinationList.add(dest);
}
}
/***************************************************************
getCityNames
Use: Loops through the array of Destination objects and creates
an array of String objects from the city names
Parameters: Takes no parameters.
Returns: cities - An array of String objects representing the
destination cities.
Notes: The cities array can be sorted in ascending order.
***************************************************************/
public String[] getCityNames()
{
// Create an array of type Destination called destinationArray.
// Convert the ArrayList destinationList to an array.
Destination[] destinationArray = (Destination[]) destinationList.toArray(new
// Create a Destination array the size of destinationList.
Destination[destinationList.size()]);
// Create a String array, cities of size destinationList.
String[] cities = new String[destinationList.size()];
// Loop the contents of the array destinationArray into array cities.
for (int i = 0; i < destinationArray.length; i++)
{
// Load contents of destinationArray into cities by calling method getCity.
cities[i] = destinationArray[i].getCity();
}
// Call Array class method sort, passing it cities.
Arrays.sort(cities);
// Return the String array containing destination cities.
return cities;
}
/***************************************************************
redeemMiles
Use: Returns an array of String objects containing descriptions of
redeemed tickets to be printed out by the main program. Also
saves the miles remaining after the tickets have been redeemed.
Parameters: 1. miles - an int representing the total available
miles.
2. month - an int representing the desired month
of departure.
Returns: results - an array of String objects containing
descriptions of redeemed tickets to be printed out by the main
program.
Notes: This method calls some of the get methods of class
Destination.
***************************************************************/
public String[] redeemMiles(int miles, int month)
{
// Call the sort method for destinationList, passing it MileageComparator.
destinationList.sort(new MileageComparator());
// Set i equal to 0.
int i = 0;
// Set remainingMiles equal to miles.
remainingMiles = miles;
// Create a String array results of size of destinationList.
String[] results = new String[destinationList.size()];
// Advanced for loop - for each destination of list destinationList.
for (Destination eachDestination : destinationList)
{
// Check the month range for each destination.
if (eachDestination.getbeginMonth() <= month && eachDestination.getendMonth() >= month)
{
// If cheapMiles are less than remainingMiles,
if (eachDestination.getCheapMiles() < remainingMiles)
{
// subtract them from remainingMiles and apply them - select destination.
remainingMiles-= eachDestination.getCheapMiles();
// Put the selected destination in array results (this is for an Economy Class flight).
results[i] = "* A trip to " + eachDestination.getCity() + " in Economy Class";
// If remainingMiles are greater than additionalMiles, traveler can upgrade.
if (remainingMiles > eachDestination.getAdditionalMile())
{
// Subtract additionalMiles and apply them - select destination, upgrading
// traveler to First Class.
remainingMiles-= eachDestination.getAdditionalMile();
// Put the selected destination in array results (this is for a First Class flight).
results[i] = "* A trip to " + eachDestination.getCity() + " in First Class";
}
}
}
// If NormalMiles are less than remainingMiles,
else if (eachDestination.getNormalMiles() < remainingMiles)
{
// apply remaining miles and tell traveler where he/she is going.
// Store selection in array results.
results[i] = "* A trip to " + eachDestination.getCity() + " in Economy Class";
// Subtract NormalMiles of the destination from remainingMiles.
remainingMiles-= eachDestination.getNormalMiles();
// If remainingMiles are greater than AdditionalMiles,
if (remainingMiles > eachDestination.getAdditionalMile())
{
// subtract AdditionalMiles from remainingMiles.
remainingMiles-= eachDestination.getAdditionalMile();
// Put the selected destination in array results (this is for a First Class flight).
results[i] = "* A trip to " + eachDestination.getCity() + " in First Class";
}
}
// Increment i.
i++;
}
// Return results.
return results;
}
/***************************************************************
getRemainingMiles
Use: Returns the saved remaining miles.
Parameters: Takes no parameters.
Returns: remainingMiles - An int representing the saved remaining
miles.
Notes: This is a class MileRedeemer getter method.
***************************************************************/
public int getRemainingMiles()
{
// Return the saved remaining miles.
return remainingMiles;
}
/***************************************************************
class MileageComparator
Use: Object of a class that defines the ordering.
Parameters: Takes no parameters, however implements a Comparator
of type Destination. Compare has two int parameters, d1 and d2
(Destination objects) - NormalMiles will be determined by
subtracting them.
Returns: the difference of the normalMiles (normal miles) for
Destination objects d1 and d2,
(d2.getNormalMiles() - d1.getNormalMiles()).
Notes: class MileageComparator has been placed in class
MileRedeemer.
***************************************************************/
// class MileageComparator implements a Comparator of type
// Destination.
public class MileageComparator implements Comparator<Destination>
{
// Compare Destination objects d1 and d2.
public int compare(Destination d1, Destination d2)
{
// Return the difference of the distances between Destination objects
// d1 and d2.
return (d2.getNormalMiles() - d1.getNormalMiles());
}
}
}
public class Destination
{
private String city; // From here and below are private instance
// variables for class Destination.
private int normalMile;
private int cheapMile;
private int additionalMile;
private String months;
private int beginMonth;
private int endMonth;
/***************************************************************
Constructor
Use: Initializes a the instance variables of a Destination
object.
Parameters: 1. City - a String that represents
where a traveler can go to.
2. normalMile - a String that represents
the normal miles for an economy class ticket.
3. cheapMile - a String that represents
the "Fly Cheap" miles needed for an economy class ticket.
4. additionalMile - a String that represents
the additional miles needed to upgrade to first/business class.
5. months - a String representing the months of
departure when the "Fly Cheap" mileage can be used.
Returns: Does not apply - constructors have NO return type.
Notes: Constructor initializes Destination instance variables
and splits a range of months of departure, storing them
into two array elements.
***************************************************************/
public Destination(String City, String normalMile, String cheapMile, String additionalMile, String months)
{
this.city = City; // Initialize City
this.normalMile = Integer.parseInt(normalMile); // Initialize noramMile
this.cheapMile = Integer.parseInt(cheapMile); // Initialize cheapMile
this.additionalMile = Integer.parseInt(additionalMile); // Initialize additionalMile
this.months = months;
// Create a String array in which to store the month range.
String[] monthRange = new String[2];
// Split month range into two months by the "-" delimiter.
monthRange = months.split("-");
// Store the first month of a departure month range in beginMonth, having parsed it.
beginMonth = Integer.parseInt(monthRange[0]);
// Store the ending month of a departure month range in endMonth, having parsed it.
endMonth = Integer.parseInt(monthRange[1]);
}
/***************************************************************
getCity
Use: Accessor method that returns the destination
city.
Parameters: Takes no parameters.
Returns: A String city - the destination city.
Notes: This is a class Destination getter method.
***************************************************************/
public String getCity()
{
// Return the destination city.
return city;
}
/***************************************************************
getNormalMiles
Use: Accessor method that returns the normal miles for an
economy class ticket.
Parameters: Takes no parameters.
Returns: An int normalMile - the normal miles for an economy
class ticket.
Notes: This is a class Destination getter method.
***************************************************************/
public int getNormalMiles()
{
// Return the normal miles for an economy class ticket.
return normalMile;
}
/***************************************************************
getCheapMiles
Use: Accessor method that returns the cheap miles for an
economy class ticket.
Parameters: Takes no parameters.
Returns: An int cheapMile - the cheap miles for an economy
class ticket.
Notes: This is a class Destination getter method.
***************************************************************/
public int getCheapMiles()
{
// Return the normal miles for an economy class ticket.
return cheapMile;
}
/***************************************************************
getAdditionalMile
Use: Accessor method that returns the additional miles needed
to upgrade to business/first class.
Parameters: Takes no parameters.
Returns: An int additionalMile - the additional miles needed to
upgrade to business/first class.
Notes: This is a class Destination getter method.
***************************************************************/
public int getAdditionalMile()
{
// Return the additional miles needed to upgrade to first class.
return additionalMile;
}
/***************************************************************
getbeginMonth
Use: Accessor method that returns the first month of a departure
month range.
Parameters: Takes no parameters.
Returns: An int beginMonth - the first month of a departure
month range.
Notes: This is a class Destination getter method.
**************************************************************/
public int getbeginMonth()
{
// Return the first month of a departure month range.
return beginMonth;
}
/***************************************************************
getendMonth
Use: Accessor method that returns the ending month of a
departure month range.
Parameters: Takes no parameters.
Returns: An int endMonth - the ending month of a departure
month range.
Notes: This is a class Destination getter method.
**************************************************************/
public int getendMonth()
{
// Return the ending month of a departure month range.
return endMonth;
}
}
Mile Redemption App Destinations Redeem Miles Berlin Hong Kong Hyderabad Sidney Paris New York Tokyo Vienna Washington, D.C Enter your miles elect the month of departure Jan Redeem miles Normal miles50000 Supersaver miles 30000 upgrade cost 20000 Supersaver DatesMay June Your remaining milesExplanation / Answer
MileRedemptionApp.java
-----------------------------------------
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpinnerListModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class MileRedemptionApp extends JFrame {
// Variables - declaration and initialization
private static Scanner fileScanner = null;
private static String[] destinationCity = null, listOfTickets = null;
private static String tkt = "";
// Object instance of MileRedeemer class created to call its methods
private static MileRedeemer mileRedeemer = new MileRedeemer();
Destination destination = null;
// Fields Declaration
final JLabel comment = new JLabel(
" Your miles can be used to redeem the following tickets:");
final JLabel remMilesLabel = new JLabel("Congrats! Your Remianing Miles is");
JTextArea ticketArea = new JTextArea();
JList listBox;
JButton button;
JTextField text1, text2, text3, text4, remMiles = new JTextField("", 10);
@SuppressWarnings("unchecked")
public MileRedemptionApp() {
// Setting the container's properties .
this.setSize(710, 380);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridLayout(0, 2));
this.setBackground(Color.red);
this.setResizable(false);
// Creating new panel and adding it.
JPanel leftPane = new JPanel();
JPanel rightPane = new JPanel();
this.add(leftPane);
this.add(rightPane);
// Setting background colors and layout for the panes
leftPane.setBackground(Color.getHSBColor(30, 100, 90));
rightPane.setBackground(Color.getHSBColor(30, 0, 90));
leftPane.setLayout(new GridLayout(2, 0, 20, 20));
rightPane.setLayout(new GridLayout(2, 0, 20, 20));
// Setting title borders for the panes
leftPane.setBorder(BorderFactory
.createTitledBorder("List of Destination Cities"));
rightPane.setBorder(BorderFactory.createTitledBorder("Redeem Tickets"));
// Creating 4 panels, setting the bkg color & layout and adding it
final JPanel leftTopPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
leftPane.add(leftTopPanel);
leftTopPanel.setBackground(Color.white);
final JPanel leftBottomPanel = new JPanel(new GridLayout(0, 2));
leftPane.add(leftBottomPanel);
leftBottomPanel.setBackground(Color.getHSBColor(30, 100, 80));
final JPanel rightTopPanel = new JPanel(new FlowLayout(
FlowLayout.CENTER));
rightPane.add(rightTopPanel);
rightTopPanel.setBackground(Color.getHSBColor(30, 0, 75));
final JPanel rightBottomPanel = new JPanel(new FlowLayout(
FlowLayout.CENTER));
rightPane.add(rightBottomPanel);
rightBottomPanel.setBackground(Color.white);
// Create a new listbox control for displaying destination cities
final JList listBox = new JList(destinationCity);
listBox.setFixedCellWidth(330);
leftTopPanel.add(listBox);
// Creating 2 panels each for label and textfields respectively
JPanel labelPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
leftBottomPanel.add(labelPanel);
labelPanel.setBackground(Color.getHSBColor(30, 100, 80));
JPanel textFieldPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
leftBottomPanel.add(textFieldPanel);
textFieldPanel.setBackground(Color.getHSBColor(30, 100, 80));
// Creating the required labels, textfields & setting its font & size
JLabel label1 = new JLabel("Required Miles");
label1.setFont(new Font("Serif", Font.PLAIN, 15));
text1 = new JTextField("", 14);
JLabel label2 = new JLabel("Miles for upgrading");
label2.setFont(new Font("Serif", Font.PLAIN, 15));
text2 = new JTextField("", 14);
JLabel label3 = new JLabel("Miles for Supersaver");
label3.setFont(new Font("Serif", Font.PLAIN, 15));
text3 = new JTextField("", 14);
JLabel label4 = new JLabel("Months for Supersaver");
label4.setFont(new Font("Serif", Font.PLAIN, 15));
text4 = new JTextField("", 14);
// Setting the text fields to non editable forms
text1.setEditable(false);
text2.setEditable(false);
text3.setEditable(false);
text4.setEditable(false);
// Adding labels and textfields to the panels
labelPanel.add(label1);
textFieldPanel.add(text1);
labelPanel.add(label2);
textFieldPanel.add(text2);
labelPanel.add(label3);
textFieldPanel.add(text3);
labelPanel.add(label4);
textFieldPanel.add(text4);
listBox.addListSelectionListener(new ListSelectionListener() {
// Method to get invoked when a city is chosen from the list
public void valueChanged(ListSelectionEvent event) {
// it will return if the value is changed
if (event.getValueIsAdjusting())
return;
// Getting the miles details of a city
destination = mileRedeemer.getMileDetails(listBox
.getSelectedValue().toString());
// Setting the text to details respective to the cities
text1.setText(String.valueOf(destination.getNormalMiles()));
text2.setText(String.valueOf(destination
.getUpgradingAdditionalMiles()));
text3.setText(String.valueOf(destination.getSuperSaverMiles()));
text4.setText(mileRedeemer.getMonthDetails(destination
.getStartMonth())
+ " to "
+ mileRedeemer.getMonthDetails(destination
.getEndMonth()));
}
});
// Setting the label and textfield for accumulated miles
JLabel accumulatedMiles = new JLabel("Your Accumulated Miles");
final JTextField accumulatedMilesText = new JTextField("", 10);
// Setting the label and spinner for departure month
JLabel departureMonth = new JLabel("Month of Departure");
SpinnerListModel monthModel = new SpinnerListModel(
mileRedeemer.getMonthStrings());
final JSpinner spinner = new JSpinner(monthModel);
spinner.setPreferredSize(new Dimension(130, 20));
// Creating the button that invokes the required method
JButton button = new JButton("Redeem Tickets >>>");
// Adding the fields
rightTopPanel.add(accumulatedMiles);
rightTopPanel.add(accumulatedMilesText);
rightTopPanel.add(departureMonth);
rightTopPanel.add(spinner);
rightTopPanel.add(button);
button.addActionListener(new ActionListener() {
// Method that is invoked when the buton is clicked
public void actionPerformed(ActionEvent arg0) {
// Adding the comment section to the panel
rightBottomPanel.add(comment);
// Setting the redeemable tickets to null
tkt = "";
// Setting the visibility of elements to false first
comment.setVisible(false);
ticketArea.setVisible(false);
remMilesLabel.setVisible(false);
remMiles.setVisible(false);
// Getting the month value in number from the spinner
int month = mileRedeemer.getMonthNumber((String) spinner
.getValue());
// Getting miles from the textfield & checking its validity
String milesValue = accumulatedMilesText.getText();
boolean match = milesValue.matches("[0-9]*");
// Continued if its a number
if (match) {
// Converting the miles value to int
int accumulatedMiles = Integer.parseInt(milesValue);
// Getting the list of redeemed tickets
listOfTickets = mileRedeemer.redeemMiles(accumulatedMiles,
month);
// Setting the comment section to true
comment.setVisible(true);
// Traversing through String array and printing the
// redeemable tickets
if (listOfTickets[0] != null) {
for (String ticket : listOfTickets)
if (ticket != null)
tkt = tkt.concat(ticket + " ");
} else
tkt = "You need more miles to redeem a ticket";
// Setting the text area with the tickets
ticketArea.setText(tkt);
// Adding the tickets and setting it to visible
rightBottomPanel.add(ticketArea);
ticketArea.setVisible(true);
// Adding the Rem miles label and setting it to visible
rightBottomPanel.add(remMilesLabel);
remMilesLabel.setVisible(true);
// Adding the rem miles text to visible and non editable
remMiles.setText("" + mileRedeemer.getRemainingMiles());
remMiles.setEditable(false);
remMiles.setVisible(true);
rightBottomPanel.add(remMiles);
} else
System.out
.println("Please enter a number in the accumulated miles field");
}
});
}
public static void main(String args[]) throws Exception {
// To check the number of arguments that is passed to the method
if (!(args[0].equals(""))) // The file from the file's location passed
// thru the args is stored
fileScanner = new Scanner(new File(args[0]));
else {
System.err
.println("Provide only one argument containing the file's location.");
System.exit(0);
}
// Methods of MileRedeemer class are called by the object's instance
mileRedeemer.readDestinations(fileScanner);
destinationCity = mileRedeemer.getCityNames();
// Swing Utility method to synchronize with the user's action
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
// Create an instance of the test application
new MileRedemptionApp();
}
});
}
}
-----------------------------------------------------------------------------------
MileRedeemer.java
-------------------------------
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;
public class MileRedeemer {
// Constants - declaration and initialization
private static final String ECONOMY = "economy";
private static final String FIRST = "first";
// Variables - declaration and initialization
private int key = 0, index = 0, lastIndex = 0, redeemedTicketsLength = 0,
destinationLength = 0, normalMiles = 0, superSaverMiles = 0,
upgradedMiles = 0, remainingMiles = 0;
private boolean superSaverEligible = false;
private String destinationObject = null;
private String[] destinationObjects = null, redeemedTickets = null,
ticketClass = null;
private List<Destination> destinationArrayList = new ArrayList<Destination>();
private Destination[] destinationList;
/**
* This method reads the file from the location provided in the args[],
* converts to String array & also to an object of a list of Destination
*/
public void readDestinations(Scanner fileScanner) {
// Checking of the file has more lines
while (fileScanner.hasNext()) {
// Storing a single line to the String
destinationObject = fileScanner.nextLine();
// Finding the lindex of last occuring '-'
lastIndex = destinationObject.lastIndexOf("-");
// Replacing '-' with ';', splitting at ';' & storing as arrays
destinationObjects = (new StringBuilder(destinationObject).replace(
lastIndex, lastIndex + 1, ";").toString()).split(";");
// Adding the array to an instance object of a list of Destination
destinationArrayList.add(new Destination(
destinationObjects[index++], Integer
.parseInt(destinationObjects[index++]), Integer
.parseInt(destinationObjects[index++]), Integer
.parseInt(destinationObjects[index++]), Integer
.parseInt(destinationObjects[index++]), Integer
.parseInt(destinationObjects[index])));
// Resetting the index to zero for the next loop
index = 0;
}
}
/**
* This method reads destinationArrayList object and stores only the
* destination in the destinationObjects array and sorts it too.
*/
public String[] getCityNames() {
// Setting the size of the array to that of the arraylist object
destinationObjects = new String[destinationArrayList.size()];
// Storing the destination city to the destinationObjects array
for (Destination dest : destinationArrayList) {
destinationObjects[index++] = dest.getDestinationCity();
}
Arrays.sort(destinationObjects);
return destinationObjects;
}
/**
* This method reads destinationArrayList object and returns the mile
* details of the city.
*/
public Destination getMileDetails(String selectedCity) {
Destination destination = null;
// Storing the destination city to the destinationObjects array
for (Destination destn : destinationArrayList)
if (selectedCity.equals(destn.getDestinationCity()))
destination = destn;
return destination;
}
/**
* This method reads month(number) of supersaver of the destination city and
* returns the corresponding Month details in words.
*/
public String getMonthDetails(int month) {
String monthString;
switch (month) {
case 1:
monthString = "January";
break;
case 2:
monthString = "February";
break;
case 3:
monthString = "March";
break;
case 4:
monthString = "April";
break;
case 5:
monthString = "May";
break;
case 6:
monthString = "June";
break;
case 7:
monthString = "July";
break;
case 8:
monthString = "August";
break;
case 9:
monthString = "September";
break;
case 10:
monthString = "October";
break;
case 11:
monthString = "November";
break;
case 12:
monthString = "December";
break;
default:
monthString = "Invalid month";
break;
}
return monthString;
}
/**
* This method reads month details in words as the input and returns its
* corresponding number.
*/
public int getMonthNumber(String monthValue) {
Date date = null;
try {
date = new SimpleDateFormat("MMM", Locale.ENGLISH)
.parse(monthValue);
} catch (ParseException e) {
System.out.println(e.getMessage());
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH) + 1;
return month;
}
/**
* The month Strings can be obtained in this method.
*
*/
public String[] getMonthStrings() {
String[] months = new java.text.DateFormatSymbols().getMonths();
int lastIndex = months.length - 1;
if (months[lastIndex] == null || months[lastIndex].length() <= 0) {
String[] monthStrings = new String[lastIndex];
System.arraycopy(months, 0, monthStrings, 0, lastIndex);
return monthStrings;
} else { // if last item not empty
return months;
}
}
/**
* This method consturcts the destinationList object from arraylist & sorts
* it. It also sends back a list of redeemable ticket information
*
*/
public String[] redeemMiles(int miles, int month) {
// Converting destinationArrayList to an object instance of Destination
destinationList = (Destination[]) destinationArrayList
.toArray(new Destination[destinationArrayList.size()]);
// Sorting the destinationList in the descending order of normal miles
Arrays.sort(destinationList, new Comparator<Destination>() {
public int compare(Destination destination1,
Destination destination2) {
return destination2.getNormalMiles()
- destination1.getNormalMiles();
}
});
// Calling the method which handles all the logic of redeeming tickets
redeemLogic(miles, month);
// Constructing the list of redeemable tickets information
for (index = 0; index < redeemedTickets.length; index++) {
if (redeemedTickets[index] != null)
redeemedTickets[index] = "* A trip to "
+ redeemedTickets[index] + ", " + ticketClass[index]
+ " class.";
}
return redeemedTickets;
}
/**
* This method calculates whether user is eligible to use super saver miles,
* checks for upgradation of ticket & also calculates the remaining miles
*/
public void redeemLogic(int miles, int month) {
// Assigning the destinationLength also to both the other arrays
key = 0;
destinationLength = destinationList.length;
redeemedTickets = new String[destinationLength];
ticketClass = new String[destinationLength];
for (index = 0; index < destinationLength; index++) {
// Supersaver logic for months, if its in the range of 1-12
if ((destinationList[index].getEndMonth() - destinationList[index]
.getStartMonth()) >= 0) {
if ((month >= destinationList[index].getStartMonth())
&& (month <= destinationList[index].getEndMonth()))
superSaverEligible = true;
else
superSaverEligible = false;
} else { // Supersaver logic for months, if its in the range of
// 12-11
if ((month < destinationList[index].getStartMonth())
&& (month > destinationList[index].getEndMonth()))
superSaverEligible = false;
else
superSaverEligible = true;
}
normalMiles = destinationList[index].getNormalMiles();
superSaverMiles = destinationList[index].getSuperSaverMiles();
// Checking for enough superSaverMiles, if travel is in super saver
// month
if ((superSaverEligible == true) && (miles >= superSaverMiles)) {
redeemedTickets[key] = destinationList[index]
.getDestinationCity();
miles = miles - superSaverMiles;
ticketClass[key++] = ECONOMY; // Economy class set for
// redeemable tickets
} // Checking for enough normalMiles, if travel isn't in super saver
// month
else if ((superSaverEligible == false) && (miles >= normalMiles)) {
redeemedTickets[key] = destinationList[index]
.getDestinationCity();
miles = miles - normalMiles;
ticketClass[key++] = ECONOMY;
}
}
redeemedTicketsLength = redeemedTickets.length;
for (index = 0; index < destinationLength; index++) {
for (key = 0; key < redeemedTicketsLength; key++) {
upgradedMiles = destinationList[index]
.getUpgradingAdditionalMiles();
// Checking for miles to upgrade the redeemable tickets to first
// class
if ((destinationList[index].getDestinationCity()
.equals(redeemedTickets[key]))
&& (miles >= upgradedMiles)) {
ticketClass[key] = FIRST; // Overriding the value from
// economy to first
miles = miles - upgradedMiles;
}
}
}
remainingMiles = miles; // The miles subtracted above is the remaining
// miles
}
public int getRemainingMiles() {
return remainingMiles;
}
}
---------------------------------------------------------------------------------------
Destination.java
--------------------------------------------
public class Destination {
// Variables - declaration
private String destinationCity;
private int normalMiles, superSaverMiles, upgradingAdditionalMiles,
startMonth, endMonth;
// Constructor
public Destination(String city, int miles, int superMiles,
int upgradingMiles, int startingMonth, int endingMonth) {
destinationCity = city;
normalMiles = miles;
superSaverMiles = superMiles;
upgradingAdditionalMiles = upgradingMiles;
startMonth = startingMonth;
endMonth = endingMonth;
}
// Getters and Setters
public String getDestinationCity() {
return destinationCity;
}
public void setDestinationCity(String destinationCity) {
this.destinationCity = destinationCity;
}
public int getNormalMiles() {
return normalMiles;
}
public void setNormalMiles(int normalMiles) {
this.normalMiles = normalMiles;
}
public int getUpgradingAdditionalMiles() {
return upgradingAdditionalMiles;
}
public void setUpgradingAdditionalMiles(int upgradingAdditionalMiles) {
this.upgradingAdditionalMiles = upgradingAdditionalMiles;
}
public int getSuperSaverMiles() {
return superSaverMiles;
}
public void setSuperSaverMiles(int superSaverMiles) {
this.superSaverMiles = superSaverMiles;
}
public int getStartMonth() {
return startMonth;
}
public void setStartMonth(int startMonth) {
this.startMonth = startMonth;
}
public int getEndMonth() {
return endMonth;
}
public void setEndMonth(int endMonth) {
this.endMonth = endMonth;
}
}
----------------------------------------------------------------
miles.txt
------------------------------
Sidney;50000;30000;20000;5-6
Hyderabad;30000;20000;15000;2-4
Chennai;20000;15000;10000;2-3
New York;10000;5000;8000;10-11
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.