Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a console-based Java application to help an airline customer find good way

ID: 3856279 • Letter: W

Question

Write a console-based Java application to help an airline customer find good ways of redeeming his/her accumulated mileage into airline tickets. Assume all trips depart from O'Hare (ORD). Different destinations need different mileage for redeeming tickets. If the person doesn't travel in a busy season, he or she may take advantage of the “Fly Cheap” program that can attain a ticket with fewer accumulated miles.

A list of destination cities and related ticket redemption information should be read from a file, which is formatted as one city per line, with five fields separated by a semicolon ( ; ) as shown below destination; normal mileage needed for an economy class ticket (this information is proportional to the actual travel distance); “Fly Cheap” mileage needed for an economy class ticket; additional mileage needed for upgrading to first class; and the months of departure when the “Fly Cheap” mileage can be used.

For example:

Berlin;17250;12750;5250;3-5

Hong Kong;30000;20250;17500;2-4

Hyderabad;30000;20000;15000;2-4
Sidney;50000;30000;20000;5-6
Paris;20000;15000;10000;2-4
New York;10000;5000;8000;10-11

Tokyo;29000;16500;5350;2-5

Vienna;17500;12500;5000;2-4

Washington, D.C.;9000;7500;2000;10-12

Your application program should prompt the user to enter the name of the file at the keyboard. Once entered, it should be read using a Scanner object named keyScan and assigned to a String variable. Then, open another Scanner object named fileScan to read the destination lines from it. To read from an input file, you will need:

import java.io.*;

Your algorithm should 1) try to get tickets that travel the farthest, 2) use “Fly Cheap” mileage whenever possible, 3) try to display as many different tickets as possible given the information (at most, one ticket is needed for a single destination), and 4) use the remaining mileage for upgrade, if possible (try to upgrade the longest trip first).

Your program should first print out a list of the cities for the user’s information. It then loops for input and prints out tickets that can be redeemed. Accurate sample program output can be found at the end of this handout on page 4. It is recommended that you set up your output so that it looks EXACTLY like the sample provided.

Sample Accurate Program Output

Please enter the name of the file: destinations.txt

-------------------------------------------------

WELCOME TO THE JAVA AIRLINES MILES REDEMPTION APP

-------------------------------------------------

List of destination cities you can travel to:

Berlin

Hong Kong

Hyderabad

New York

Paris

Sidney

Tokyo

Vienna

Washington, D.C.

---------------------------------------------------

Please enter your accumulated Frequent Flyer Miles: 49600

Please enter your month of departure (1-12): 4

Your Frequent Flyer Miles can be used to redeem the following tickets:

* A trip to Hong Kong in Economy Class

* A trip to Hyderabad in Economy Class

* A trip to Washington, D.C., in Economy Class

Your remaining Frequent Flyer Miles: 350

Do you want to continue (y/n)? n

-----------------------------------------------------------

THANK YOU FOR USING THE JAVA AIRLINES MILES REDEMPTION APP!

-----------------------------------------------------------

Explanation / Answer

Flycheap.java
--------------------------
import java.util.Scanner; //To get input from the user
import java.io.File; //To use files
import java.io.IOException; //To handle input output exception

public class FlyCheap
{
    public static void main(String[] args) throws IOException
    {
        int numMiles, //Stores number of Miles enered ny the user
                month; //Stores month of departure
        char cont; //Stores whether the user want to continue or exit
        cont = 'y'; //intialized to y
        Scanner inputScan = new Scanner(System.in); //Scanner object created to take input from the console

        do // A do wile loop to prompt user for recommendtions multiple times
        {
            try
            {
                cont = 'n'; //value changed to n
                System.out.println("Enter the name of the file with exension"); // Prompts user to enter the filename
                String fileName = inputScan.next(); // Stores the input givn by user

                Scanner fileInput = new Scanner(new File(fileName)); //Scanner object for reading the contents of the file
                MileRedeemer redeemerObj = new MileRedeemer(); // Creates an object of MileRedeemer class

                redeemerObj.readDestinations(fileInput); // Method call to readDestinations function in MileRedeemer
                System.out.println(" ---------------------------------------------");
                System.out.println("List of destination cities you can travel to: ");
                for(String str: redeemerObj.getCityNames()) //Loop to print the city names
                {
                    System.out.println(str); //prints out each city name
                }
                System.out.println(" ---------------------------------------------");
                System.out.print(" Please input your total accumulated miles: "); // Prompts user
                numMiles = inputScan.nextInt(); //Stores input

                System.out.print(" Please input your month of departure (1-12): "); // Prompts user
                month = inputScan.nextInt(); // Stores input

                System.out.println("");
                for(String str:redeemerObj.redeemMiles(numMiles, month)) //for each loop to print values returned by redeemMiles method
                {
                    System.out.println(str);
                }
                System.out.println(" Your remaining miles: "+redeemerObj.getRemainingMiles()); //Displays the remaining miles after recommendations are made
                fileInput.close(); //close fileInput object
            }
            catch(Exception e)
            {
                System.err.println(" Encountered wrong input "+e.getMessage());
            }
            finally
            {
                System.out.print(" Do you want to continue:(y/n)?"); //Prompts user to select whether he wants to continue or not
                String str = inputScan.next(); // Stores the user input
                cont = str.charAt(0); //converts string into char

            }

        }while(cont=='y'); // If user enters y then he will again be prompted
        System.out.println(" End of appliation!"); //Displays it to user
        inputScan.close(); //closes the inputScan object

    }
}

--------------------------------------------------------
MileRedeemer.java
------------------------------
import java.util.Arrays; //To use arrays
import java.util.Collections; //To use sort method
import java.util.Comparator; //To implement Comparator interface
import java.util.Scanner; //To read streams from conole as well as file
import java.util.ArrayList; //To use ArrayList

class MileRedeemer
{

    int remainingMiles=0; //remaining miles set to 0
    String record; // To store each line from file
    ArrayList<Destination>destinationList = new ArrayList<Destination>(); // ArrayList of type Destination is created

    /*This function is used to read lines from files*/
    public void readDestinations(Scanner fileScanner)
    {
        try
        {
       /*If the file has a line then the loop is executed else no*/
            while(fileScanner.hasNext())
            {
                int normalMiles, //stores normal miles
                        supersaverMiles, //stores super saver miles
                        additionalMiles, //stores addtional miles
                        startMonth, //stores start of month
                        endMonth; //stores end of month
                String destinationCity; //stores destination city
                record = fileScanner.nextLine(); //stores the next line into record

                String[] values = record.split(";"); //splits record on encountering semi-colon
                String[] values2 = values[4].split("-"); //splits the record on encountering hipen

           /*values that are obtained after splitting the record are then stored into different variables*/
                destinationCity = values[0];
           /*strings are converted into integers using Integer.parse int and stored in variables*/
                normalMiles = Integer.parseInt(values[1]);
                supersaverMiles = Integer.parseInt(values[2]);
                additionalMiles = Integer.parseInt(values[3]);
                startMonth = Integer.parseInt(values2[0]);
                endMonth = Integer.parseInt(values2[1]);

           /*Object of type Destination is created and populated with above intialized variables*/
                Destination obj = new Destination(normalMiles,supersaverMiles,additionalMiles,startMonth,endMonth,destinationCity);

           /*This object is stored in array list*/
                destinationList.add(obj);

            }
        }
        catch(Exception e)
        {
            System.err.println("File input format wrong: "+e.getMessage());
            System.exit(0);
        }


    }

    /*getCityNames is a function which returns a String array containing Cities*/
    public String[] getCityNames()
    {
        int i = 0;
        String[] cityNames = new String[destinationList.size()]; //String array cityNmaes is created store cityNames
   /*cityNames is populated with city names using for each loop*/
        for(Destination d: destinationList)
        {
            cityNames[i] = d.getDestinationCity();
            i++;
        }
        Arrays.sort(cityNames); // cityNames is sorted in Ascending order
        return cityNames; //String array is returned
    }

    public String[] redeemMiles(int miles,int month)
    {
        int tempMiles = miles; //stores miles into another variable

        ArrayList<Destination> abc = new ArrayList<>(); //ArrayList of type destination is created
        ArrayList<String> def = new ArrayList<>(); //ArrayList of type String is created

        Collections.sort(destinationList,new MileageComparator()); // destinationList is sorted in the descending order of Normal miles
   /*For each to prse through destination list*/
        for(Destination d: destinationList)
        {
            if(month < d.getStartMonth() || month > d.getEndMonth()) //If the month is less that start month or greater than endmonth then if is executed
            {
                if(tempMiles > d.getNormalMiles())
                {
               /*if miles is greater than Normal miles then this object is added into abc arrayList*/
                    abc.add(d);
                    tempMiles-= d.getNormalMiles(); //miles is decreased by normal miles of the current instance
                }

            }
            else if(month >= d.getStartMonth() && month <= d.getEndMonth()) //If month is in super saver miles then this block is executed
            {
                if(tempMiles > d.getSuperSaverMiles())
                {
               /* If miles is greter than super saver then the miles is decresed by super saver ad the current instance of Destiantion is added into array list abc */
                    abc.add(d);
                    tempMiles -= d.getSuperSaverMiles();
                }
            }

        }

        for(Destination d: abc)
        {
       /* If the miles is greater than additional miles then ticket is redeemed to first class and miles is decreased by additional miles */
            if(tempMiles > d.getAdditionalMiles())
            {
                def.add("* A trip to "+d.getDestinationCity()+" first class"); //def is populated with strings of recommendations
                tempMiles -= d.getAdditionalMiles();
            }
            else // If miles is less than additional miles then economy class ticket is recommended
            {
                def.add("* A trip to "+d.getDestinationCity()+", economy class"); //Displays economy class with destination city
            }
        }
        remainingMiles = tempMiles; //remainingMiles is filled with mile left
        String[] details = new String[def.size()]; //String array is created
        details = def.toArray(details); //populated with arraylist of type string
        return details; //returns the details
    }


    public int getRemainingMiles()
    {
        return remainingMiles; // Returns the remaining miles
    }

}

--------------------------------------------------------
Destination.java
------------------------------
class Destination
{
    /*Variables to store values*/
    int normalMiles,
            supersaverMiles,
            additionalMiles,
            startMonth,
            endMonth;
    String destinationCity;
    /*Constructor to intialise the variables */
    Destination(int normalMiles,int supersaverMiles,int additionalMiles,int startMonth,int endMonth,String destinationCity)
    {
        this.normalMiles = normalMiles;
        this.supersaverMiles = supersaverMiles;
        this.additionalMiles = additionalMiles;
        this.startMonth = startMonth;
        this.endMonth = endMonth;
        this.destinationCity = destinationCity;
    }
    /*Used to set value of normal miles*/
    public void setNormalMiles(int normalMiles)
    {
        this.normalMiles = normalMiles;
    }
    /*method to get value of normal miles*/
    public int getNormalMiles()
    {
        return normalMiles;
    }
    /*method to set supersaver miles*/
    public void setSuperSaverMiles(int supersaverMiles)
    {
        this.supersaverMiles = supersaverMiles;
    }
    /*method to get value of supersaver miles*/
    public int getSuperSaverMiles()
    {
        return supersaverMiles;
    }
    /*method to set additional miles*/
    public void setAdditionalMiles(int additionalMiles)
    {
        this.additionalMiles = additionalMiles;
    }
    /*method to get additional miles*/
    public int getAdditionalMiles()
    {
        return additionalMiles;
    }
    /*method to set start month value*/
    public void setStartMonth(int startMonth)
    {
        this.startMonth = startMonth;
    }
    /*method to get start month value*/
    public int getStartMonth()
    {
        return startMonth;
    }
    /*method to set end month value*/
    public void setEndMonth(int endMonth)
    {
        this.endMonth = endMonth;
    }
    /*method to get end month value*/
    public int getEndMonth()
    {
        return endMonth;
    }
    /*method to set destination city*/
    public void setDestinationCity(String destinationCity)
    {
        this.destinationCity = destinationCity;
    }
    /*method to get destination city*/
    public String getDestinationCity()
    {
        return destinationCity;
    }

}

--------------------------------------------------------
MileageComparator
------------------------------
import java.util.Comparator;

class MileageComparator implements Comparator<Destination>
{
    @Override
    public int compare(Destination d1, Destination d2) //Compares attributes of two instances of Destinations
    {
        if(d1.getNormalMiles() > d2.getNormalMiles()) //compares normal miles between two intstances
        {
            return -1;
        }
        else if(d1.getNormalMiles() < d2.getNormalMiles()) //if normal miles of second instance is greater than first
        {
            return 1;
        }
        else return 0;
    }
}
----------------------------------------------------
destination.txt
-----------------
Berlin;17250;12750;5250;3-5

Hong Kong;30000;20250;17500;2-4

Hyderabad;30000;20000;15000;2-4
Sidney;50000;30000;20000;5-6
Paris;20000;15000;10000;2-4
New York;10000;5000;8000;10-11

Tokyo;29000;16500;5350;2-5

Vienna;17500;12500;5000;2-4

Washington, D.C.;9000;7500;2000;10-12

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote