Как разобрать строку на несколько массивов

#java

#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
  

Короче говоря, формат:
СЧЕТЧИК -> КУПЛЕННЫЕ ТОВАРЫ -> ТЕНДЕР

Я пытался это сделать, но это не настолько эффективно:

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

Как я могу прочитать файл и в то же время гарантировать, что я помещу его в правильный массив? Помимо счетчика и тендера, мне нужно знать название книги и количество, чтобы я мог получить ее цену и компьютер для общей цены. Нужно ли мне создавать несколько массивов для хранения каждого значения? Любые предложения / коды будут
высоко ценится.

Спасибо.

Комментарии:

1. Обратите внимание на пробел перед tender во второй строке.

Ответ №1:

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

Ответ №2:

Как насчет этого? Здесь у нас есть класс, который моделирует покупку, содержащий счетчик, тендер и список купленных товаров. Купленный товар состоит из идентификатора (например, 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;
    }
}