Mooc.fi Java 1 -Part07_07 食谱

问题描述 投票:0回答:1

(对格式表示歉意,这是我的第一篇文章)

我正在考虑通过赫尔辛基大学的 mooc.fi Java 自学 Java, 我连续 4 天一直在尝试这个问题,但就是无法解决它。这个问题要求我从列表中读取食谱(食谱包括名称、烹饪时间、成分都在单独的行上),食谱之间用空行分隔,文本文件如下。

Pancake dough 
60 
milk
egg
flour 
sugar 
salt 
butter

Meatballs 
20 
ground 
meat 
egg 
breadcrumbs

Tofu rolls 
30 
tofu rice 
water 
carrot 
cucumber 
avocado 
wasabi

它保存了正确数量的食谱,但它们都有相同的输出。我的输出如下

Pancake dough, cooking time: 60 
Pancake dough, cooking time: 60 
Pancake dough, cooking time: 60 

输出应该是。

Pancake dough, cooking time: 60 
Meatballs, cooking time: 20 
Tofu rolls, cooking time: 30 

我的主要方法。

public UserInterface(){

}

public void start(){

 ArrayList<Recipe> book = new ArrayList<>();

 String row="" ;

 try (Scanner scanner = new Scanner(Paths.get("recipes.txt"))){
     ArrayList<String> item = new ArrayList<>();

     
     while (scanner.hasNextLine()){

     
     while (scanner.hasNextLine()) {
         row = scanner.nextLine();
         if (row.equals("")) {
             break;
             
         }else{
             item.add(row);

         }

     }
         book.add(new Recipe(item));

     }
     
 } catch (Exception e) {
 }
 
 for (int i = 0; i < book.size(); i++) {
     System.out.println(book.get(i).list());
     
 }
}

}

食谱课。

import java.util.ArrayList;

public class Recipe {

private String name;
private int cookingTime;
private ArrayList<String> recipe;

public Recipe(ArrayList<String> r){
    this.recipe = r;



}

public String list(){
    return(this.recipeName()+", cooking time: "+this.cookingTime());
}

public String recipeName(){
    return this.recipe.get(0);
}

public int cookingTime(){
    return Integer.valueOf(this.recipe.get(1));

}
}

您的帮助将不胜感激

我尝试用扫描仪读取图纸行, 保存到数组列表中的行 一旦扫描仪检测到空白区域,它就应该将 arrayList 保存到配方对象中。 然后从下一行继续并重复。

java object arraylist
1个回答
0
投票

items
列表的实例化位于错误的位置(1)。因此,这个列表变得越来越长,而第一个食谱仍然位于顶部。请注意输出如何显示重复多次的first配方。

每次有新食谱时,您都需要创建一个新的

items
列表......即在(2)处。

        try (Scanner scanner = new Scanner(Paths.get("recipes.txt"))) {
            // (1) Wrong here: ArrayList<String> item = new ArrayList<>();

            while (scanner.hasNextLine()) {
                // (2) should be here:
                ArrayList<String> item = new ArrayList<>();

                while (scanner.hasNextLine()) {
                    row = scanner.nextLine();
                    if (row.equals("")) {
                        break;

                    } else {
                        item.add(row);

                    }
                }
                book.add(new Recipe(item));
                // (3)
            }
        }

您应该尝试另一个“解决方案”,看看会发生什么:将代码保留在 (1) 处,并在实例化 Recipe (3) 后调用

items.clear()
。会发生什么?为什么?

© www.soinside.com 2019 - 2024. All rights reserved.