首页 > 解决方案 > 如何将文本文件中的数据集以空行分隔

问题描述

我有一个包含膳食食谱的文本文件,其中每个食谱用空行分隔。食谱由名称、烹饪时间和配料组成,所有这些都在单独的一行中。th=is 之后是一个空行,然后下一个配方将随之而来。

我创建了一个食谱类来存储每个食谱和一个食谱管理器类,然后将所有食谱存储在一个列表中,并且还将包含各种方法来根据成分等字段搜索食谱。

我有一种方法可以在第一个空白行之前读取第一个食谱,然后将数据放在一个临时列表中,然后使用它为食谱创建 Recipe 对象,然后将其存储在将保存食谱列表的 RecipeManager 对象中. 我需要一次从 txt 文件(以空行分隔)中读取食谱,这就是我需要一些帮助和指导的地方。下面是txt文件和相关的类文件。

食谱.txt:

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

用户界面.java

public class UserInterface {
    private Scanner scanner;
    private RecipesManager manager; //object to hold list of recipes with access to varous methods to search for recipes

    public UserInterface(Scanner scanner, RecipesManager manager) {
        this.scanner = scanner;
        this.manager = manager;
    }
    
    public void start(){
        System.out.println("File to read: ");
        String input = scanner.nextLine();
        System.out.println("Commands: ");
        System.out.println("list - lists the recipes");
        System.out.println("stop - stops the program");
        readFile(input);
        
    }
    
    private void readFile(String fileName){ //method to read the recipes from the text file
        ArrayList<String> recipe = new ArrayList<>(); //List to store recipe that is to be read
        try {
            Scanner file = new Scanner(Paths.get(fileName));
            while(file.hasNext()){
                String line = file.nextLine();
                recipe.add(line);
            }
            createRecipe(recipe);
            System.out.println(recipe);
            
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        } //currently reads all the lines in the text file but need it to read one recipe at a time 
    }
    
    private void createRecipe(ArrayList<String> recipe){ //method to create recipe object and then store in a list of recipes (RecipeManager)
        String name = recipe.get(0);
        int time = Integer.valueOf(recipe.get(1)); //convert the time in String format to Integer
        ArrayList<String> ingredients = new ArrayList<>(); //list of ingredients
        for(int i=2; i<recipe.size(); i++){ //add ingredients found from index 2 onwards, to the ingredients list
            ingredients.add(recipe.get(i));
        }
        
        manager.addRecipe(new Recipe(name, time, ingredients)); //add to the list of recipes in the RecipeManager object
    }
    
}  

标签: java

解决方案


推荐阅读