开发者

How to parse a String into multiple arrays

开发者 https://www.devze.com 2023-03-04 22:22 出处:网络
Good day! I am making a mini bookstore program and we are required to read a file based from what the customer buys on the specified cou开发者_开发知识库nter as follows:

Good day!

I am making a mini bookstore program and we are required to read a file based from what the customer buys on the specified cou开发者_开发知识库nter as follows:

counter 4,book1 2,book2 2,book3 2,tender 100.00
counter 1,book1 2,book2 1,book3 3, book4 5,tender 200.00
counter 1,book3 1,tender 50.00

In short the format is: COUNTER -> ITEMS BOUGHT -> TENDER

I tried doing this but it is not that efficient:

public List<String> getOrder(int i) {
        List <String> tempQty = new ArrayList<String>();
        String[] orders = orderList.get(0).split(",");
        for (String order : orders) {
            String[] fields = order.split(" ");
            tempQty.add(fields[i]);
        }
        return tempQty;
}

How can i read the file and at the same time, ensures that I will put it on the correct array? Besides the counter and the tender, I need to know the name of the book and the qty so I could get its price and computer for the total price. Do I need to do multiple arrays to store each values? Any suggestions/ codes will be highly appreciated.

Thank you.


    Map<String, Integer> itemsBought = new HashMap<String, Integer>();
    final String COUNTER = "counter";
    final String TENDER = "tender";
    String[] splitted = s.split(",");
    for (String str : splitted) {
        str = str.trim();
        if (str.startsWith(COUNTER)) {
            //do what you want with counter
        } else if (str.startsWith(TENDER)) {
            //do what you want with tender
        } else {
            //process items, e.g:
            String[] itemInfo = str.split(" ");
            itemsBought.put(itemInfo[0], Integer.valueOf(itemInfo[1]));
        }
    }


How about this? Here we have a class that is modeling a purchase, containing counter, tender and a list of the bought items. The bought item consists of an id (e.g. book1) and a quantity. Use the method readPurchases() to read the contents of a file and get a list of purchases.

Does this solve your problem?

public class Purchase {
    private final int counter;
    private final List<BoughtItem> boughtItems;
    private final double tender;

    public Purchase(int counter, List<BoughtItem> boughtItems, double tender) {
        this.counter = counter;
        this.boughtItems = new ArrayList<BoughtItem>(boughtItems);
        this.tender = tender;
    }

    public int getCounter() {
        return counter;
    }

    public List<BoughtItem> getBoughtItems() {
        return boughtItems;
    }

    public double getTender() {
        return tender;
    }
}

public class BoughtItem {
    private final String id;
    private final int quantity;

    public BoughtItem(String id, int quantity) {
        this.id = id;
        this.quantity = quantity;
    }

    public String getId() {
        return id;
    }

    public int getQuantity() {
        return quantity;
    }
}

public class Bookstore {

    /**
     * Reads purchases from the given file.
     * 
     * @param file The file to read from, never <code>null</code>.
     * @return A list of all purchases in the file. If there are no
     *         purchases in the file, i.e. the file is empty, an empty list
     *         is returned
     * @throws IOException If the file cannot be read or does not contain
     *                     correct data.
     */
    public List<Purchase> readPurchases(File file) throws IOException {

        List<Purchase> purchases = new ArrayList<Purchase>();

        BufferedReader lines = new BufferedReader(new FileReader(file));
        String line;
        for (int lineNum = 0; (line = lines.readLine()) != null; lineNum++) {

            String[] fields = line.split(",");
            if (fields.length < 2) {
                throw new IOException("Line " + lineNum + " of file " + file + " has wrong number of fields");
            }

            // Read counter field
            int counter;
            try {
                String counterField = fields[0];
                counter = Integer.parseInt(counterField.substring(counterField.indexOf(' ') + 1));
            } catch (Exception ex) {
                throw new IOException("Counter field on line " + lineNum + " of file " + file + " corrupt");
            }

            // Read tender field
            double tender;
            try {
                String tenderField = fields[fields.length - 1];
                tender = Double.parseDouble(tenderField.substring(tenderField.indexOf(' ') + 1));
            } catch (Exception ex) {
                throw new IOException("Tender field on line " + lineNum + " of file " + file + " corrupt");
            }

            // Read bought items
            List<BoughtItem> boughtItems = new ArrayList<BoughtItem>();
            for (int i = 1; i < fields.length - 1; i++) {
                String id;
                int quantity;
                try {
                    String bookField = fields[i];
                    id = bookField.substring(0, bookField.indexOf(' '));
                    quantity = Integer.parseInt(bookField.substring(bookField.indexOf(' ') + 1));

                    BoughtItem boughtItem = new BoughtItem(id, quantity);
                    boughtItems.add(boughtItem);
                } catch (Exception ex) {
                    throw new IOException("Cannot read items from line " + lineNum + " of file " + file);
                }
            }

            // We're done with this line!
            Purchase purchase = new Purchase(counter, boughtItems, tender);
            purchases.add(purchase);
        }

        return purchases;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消