How to sort the data of a text file in java and put the data in an array to create an object?

advertisements

I am trying to write a method that will read a text file that looks like this:

N 1000.0 NY
R 2000.0 CA 0.09
R 500.0 GA 0.07
N 2000.0 WY
O 3000.0 Japan 0.11 20.0
N 555.50 CA
O 3300.0 Ecuador 0.03 30.0
R 600.0 NC 0.06

The starting letters are the different types of orders. Each type of order has different parameters. I want the method to read the orders from the text file in a format like this: Type Price Location [TaxRate] [Tariff]. My point of confusion is how to add the string data to the array.

public static void readOrders (String fileName)
{
    File file = new File (fileName);

    scan = null;
    try {
        scan = new Scanner(file);
    } catch (FileNotFoundException e) {
        System.out.println("Error, file not found: " + file.toString());
        e.printStackTrace();
    }

    Order[] orders = new Order[8];

    for (int i = 0; i < orders.length; i++)
    {
        String data = scan.next();
        String [] val = data.split(" ");
        // String type = ?? (val[0]);
        double price = Double.parseDouble(val[1]);
        // String location = ?? (val[2]);
        double taxRate = Double.parseDouble(val[3]);
        double tariff = Double.parseDouble(val[4]);

        Order o = new Order (type, price, location, taxRate, tariff);
        orders[i] = o;
    }
    scan.close();

    System.out.println("All Orders");
    for (Order o : orders)
        System.out.println(o);

}


You need to make the below changes in your for loop.

for (int i = 0; i < orders.length; i++) {
    String data = scan.nextLine(); // you need to use nextLine to read a whole line
    String[] val = data.split(" ");
    String type = val[0]; // Since its a String
    double price = Double.parseDouble(val[1]);
    String location = val[2];  // Since its a String
    double taxRate = 0.0; // Default values
    double tariff = 0.0; // Default values
    try { // Incase they are not present - error handling
        taxRate = Double.parseDouble(val[3]);
        tariff = Double.parseDouble(val[4]);
    } catch (ArrayIndexOutOfBoundsException e) {
    }

    orders[i] = new Order(type, price, location, taxRate, tariff);
}