如何将String解析为多个数组

时间:2011-05-11 13:19:17

标签: java

美好的一天!

我正在制作迷你书店计划,我们需要根据客户在指定柜台购买的内容阅读文件,如下所示:

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

简而言之,格式是: COUNTER - >物品买卖 - >投标

我尝试过这样做,但效率不高:

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;
}

我如何读取文件,同时确保将其放在正确的数组上?除了柜台和招标,我需要知道书的名称和数量,所以我可以得到它的价格和计算机的总价格。我是否需要执行多个数组来存储每个值?任何建议/代码都将是 非常感谢。

谢谢。

2 个答案:

答案 0 :(得分:2)

    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]));
        }
    }

答案 1 :(得分:1)

这个怎么样?在这里,我们有一个模拟购买的类,包含计数器,招标和已购买商品的列表。购买的商品包含ID(例如book1)和数量。使用方法readPurchases()来读取文件的内容并获取购买列表。

这会解决您的问题吗?

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;
    }
}