java - 如何将文本文件中的数据集以空行分隔
问题描述
我有一个包含膳食食谱的文本文件,其中每个食谱用空行分隔。食谱由名称、烹饪时间和配料组成,所有这些都在单独的一行中。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
}
}
解决方案
推荐阅读
- c# - 如何在 Realm.Net 中设置“忽略”/仅运行时的 RealmObject 成员?
- python - 配置不当:“sql_server.pyodbc”在 CentOS7 中不是可用的数据库后端
- sql - 从 3m 返回数据,或下一个可用日期
- java - 哪个相当于 Java 的“isinstance”(Python)?
- python - Anaconda Gstreamer Gst packge 缺少“jpegenc”
- chart.js - Chart.js 如何为两个数据集创建图表 wirhout y 轴
- authentication - Joomla 登录被拒绝
- r - Shiny App:在模块中进行翻译并在它们之间浏览时更新语言选择
- html - 使用网格的问题 - 居中文本和使用间隙
- swift - 尝试在 Swift MapView 中进行自定义标注并更改标记颜色