Kelli Davis
Kelli Davis

Reputation: 53

How to sort info from a text file into an array by type in java?

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 sort the data into the array by type.

public static ArrayList<Order> 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[] order = new Order[8];

    for (int i = 0; i < order.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) {
}
    ArrayList <Order> orders =new ArrayList<Order>(Arrays.asList(order));
    return orders;

I cannot get it to work with my main method:

public static void main(String[] args) 
{
    ArrayList<Order> orders2 = readOrders("orders.txt"); 

    for( Order o2 : orders2) 
    { 
        System.out.println( o2.printOrder("Long")); 
    } 

    for( Order o2 : orders2) 
    { 
        System.out.println(o2.printOrder("Short")); 
    } 

}

This is my error code:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    The method printOrder(String) is undefined for the type Order
    The method printOrder(String) is undefined for the type Order

    at prob1.OrderTester.main(OrderTester.java:19)

Upvotes: 0

Views: 868

Answers (4)

Kelli Davis
Kelli Davis

Reputation: 53

I figured out the answer I was looking for. Here it is:

public static ArrayList<Order> readOrders (String fileName)
    {
        File file = new File (fileName);
        ArrayList<Order> o = new ArrayList<Order>();

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


        while (scan.hasNext())
        {
            String fl = scan.next();

            if (fl.equals("N"))
            {
                NonProfitOrder n = new NonProfitOrder(scan.nextDouble(), scan.next());
                o.add(n);
            }
            else if (fl.equals("R"))
            {
                RegularOrder r = new RegularOrder (scan.nextDouble(), scan.next(), scan.nextDouble());
                o.add(r);
            }
            else
            {
                OverseasOrder oo = new OverseasOrder(scan.nextDouble(), scan.next(), scan.nextDouble(), scan.nextDouble());
                o.add(oo);
            }

        }
        return o;
    }

Upvotes: 0

blgt
blgt

Reputation: 8205

The best practice for sorting an array list by type is:

If it's not already, make Order implement Comparable and override compareTo(Order o) to return the following, assuming there is a String type field and it has an accessor method getType():

@Override
public int compareTo(Order o) {
    return type.compareTo(o.getType());
}

Then simply call Arrays.sort(orders) once you've scanned the file.

Or use a Comparator.

Having said that, here's a short list of some of the wrongest things in your code:

(1) You haven't posted the source for the Order class, which is the main class with regards to the question you've asked. Makes it hard to give a more specific answer.

(2) The readOrders() function you've posted either is incomplete or (even if you add the couple of missing curly braces, and close the for loop) returns a list containing 8 null references. You need to instantiate the Order objects.

(3) Why use an array Order[] instead of just using the list with ArrayList.add()?

(4) Any time the Scanner fails to load the file, it will throw a NullPointerException on the first line after the catch block.

(5) Checking if your array has ended by catching ArrayIndexOutOfBoundsException() is bad practice for a multitude of reasons. Google it if you don't believe me.

(6) You get a compilation error because the Order.printOrder(String) is not defined. Define it, or better yet override Order.toString().

Consider rewriting your code to address these issues. There's likely more, these are just the things that jump out at first glance.

Upvotes: 0

eiselems
eiselems

Reputation: 180

Like already mentioned you got a compilation error. Your Order class need to have a printOrder(String) method.

You should also check your readOrders method. It seems to always return empty Orders because you create the order array with

Order[] order = new Order[8];

But NEVER assign something with something like:

order[i] = new Order(type, price, location, etc ...);

The catch block seems also wrong

} catch (ArrayIndexOutOfBoundsException e) {

you need to close it!

Upvotes: 0

blackbird014
blackbird014

Reputation: 2069

Well. it is a compilation error. The class Order doesn't include the method you are calling. E.g.

    printOrder("Long")

Check the class Order. Here you have not provided it

Upvotes: 1

Related Questions