【问题标题】:Making an array with input from a textFile using BufferedReader使用 BufferedReader 从文本文件的输入创建一个数组
【发布时间】:2018-12-02 08:49:44
【问题描述】:

我正在制作一个文件,读取带有食谱信息的文本文件并对其进行格式化。为此,我使用了一个循环,但是我在阅读部分遇到了问题。这是我用作输入的文本文件中一个配方的示例:

"id": 44330 
"cuisine": "indian"
"ingredients": 
"butter"
"peanut butter"
"chuck"
"curry powder"
"unsalted dry roast peanuts"
"coconut milk"
"brown sugar"

这是我的代码,它应该遍历每个元素并将其存储在一个数组中。我的问题是我认为我需要制作另一组配料,因为每个食谱样本都有不同数量的配料。我不确定如何解决这个问题或如何对未指定的数组进行编码:

while (currentLine != null) {

    String[] RecipeId = currentLine.split("\\s+");
    String idName = RecipeId[0];
    int id = Integer.valueOf(RecipeId[1]);
    String cuisine = RecipeId[2];
    String cuisinetype = RecipeId[3];
    String[] ingredientsList = currentLine.split("\\s+");
    String ingredientOne = ingredientsList[];


    recipesFormat.add(new Student(idName, id,cuisine,cuisinetype));
    recipesIngredients.add(new Ingredients(ingredientsList));
}

【问题讨论】:

  • 如果我理解正确,您将拆分 currentLine 并获取索引 0 和 1 但您并不总是拥有索引 1...。顺便说一句我认为建议使用json 甚至xml...
  • (相关:Reading recipe lines.)

标签: java arrays bufferedreader


【解决方案1】:
class Receipt {

    private int id;
    private String cuisine;
    private ArrayList<String> ingredients;

    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getCuisine() { return cuisine; }
    public void setCuisine(String cuisine) { this.cuisine = cuisine; }
    public ArrayList<String> getIngredients() { return ingredients; }
    public void setIngredients(ArrayList<String> ingredients) { this.ingredients = ingredients; }

}

public List<Receipt> readReceipts() {

    List<Receipt> receipts = new ArrayList<>();
    Receipt receipt = null;

    try (BufferedReader r = new BufferedReader(new FileReader(new File("/path/to/input.txt")))) {

        String line;
        while((line = r.readLine()) != null) {

            // new receipt
            if(line.startsWith("\"id\":")) {

                // add old
                if(receipt != null)
                    receipts.add(receipt);

                receipt = new Receipt();

                receipt.setId(Integer.valueOf(line.split(":\\s*")[1].trim()));
                line = r.readLine();
                receipt.setCuisine(line.split(":\\s*")[1].replaceAll("\"", "").trim());
                line = r.readLine(); // skip this line
                receipt.setIngredients(new ArrayList<>());
            }
            else {
                receipt.getIngredients().add(line.replaceAll("\"", ""));
            }

        }

        // last fetched receipt
        receipts.add(receipt);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return receipts;

}

【讨论】:

    猜你喜欢
    • 2015-04-27
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 2012-07-20
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    相关资源
    最近更新 更多