【发布时间】:2018-09-04 04:06:54
【问题描述】:
我正在尝试从配置文件中读取行并使用add() 方法将每一行附加到ArrayList 中。
但是,当我通过使用foreach 打印ArrayList 的内容时,它只打印要输入的最后一项。在我看来, add() 方法可能没有正确附加?我还尝试使用 generic for 循环 而不是 foreach,结果仍然相同。
public static void interpret(String line){
ArrayList<String> rooms = new ArrayList<>();
ArrayList<String> rules = new ArrayList<>();
// Ignore Room and Rule templates
if(line.contains("(") && line.contains(")")){
System.out.println("skip");
return;
}
if(line.contains("Room;")){
rooms.add(line);
rooms.forEach(System.out::println);
}
if(line.contains("Rule;")){
rules.add(line);
rules.forEach(System.out::println);
}
}
输出如下。
Rule; (Room: SmartObject, state{condition}, state{condition}, ...)
skip
Rule; Garden: Sprinklers, on{time=15}, off{time=16}, off{weather="raining"}
Rule; Garden: Sprinklers, on{time=15}, off{time=16}, off{weather="raining"}
Rule; Kitchen: Coffee machine, on{time=6}, off{time=12}
Rule; Kitchen: Coffee machine, on{time=6}, off{time=12}
它与读取的文件中的实际文本行混合在一起,但正如您所见,它只打印它上面的行,这是附加到ArrayList 中的最后一行。
它应该看起来像这样。
Rule; (Room: SmartObject, state{condition}, state{condition}, ...)
skip
Rule; Garden: Sprinklers, on{time=15}, off{time=16}, off{weather="raining"}
Rule; Garden: Sprinklers, on{time=15}, off{time=16}, off{weather="raining"}
Rule; Kitchen: Coffee machine, on{time=6}, off{time=12}
Rule; Garden: Sprinklers, on{time=15}, off{time=16}, off{weather="raining"}
Rule; Kitchen: Coffee machine, on{time=6}, off{time=12}
任何帮助/见解将不胜感激。
【问题讨论】: