我正在尝试读取文件并根据文件的每一行所说的内容执行命令。 该文件如下所示:
Add saw cutting tool
Add yen a monetary unit
Add pan a dish
List
public void Load(String fileName) throws FileNotFoundException{
BufferedReader r = new BufferedReader (new FileReader(fileName));
Scanner sc = new Scanner(r);
while(sc.hasNextLine()){
while(sc.hasNext()){
String temp =sc.nextLine();
**if(temp.startsWith("Add")){
String word = sc.next().toLowerCase();
String def = sc.nextLine().toLowerCase();
Add(word, def);**
}else if(temp.equals("List")){
List();
}
}
}
}
正在打印:
Add saw cutting tool Add yen a monetary unit Add pan a dish
我希望它打印出来像:
saw cutting tool
yen a monetary unit
pan a dish
我知道问题不在印刷品中。问题出在**上面。关于我如何解决这个问题的任何建议?
答案 0 :(得分:0)
试试这个
if(temp.startsWith("Add")){
String word = sc.next().toLowerCase().replaceFirst("All", "");
String def = sc.nextLine().toLowerCase().replaceFirst("All", "");;
Add(word, def);
}
答案 1 :(得分:0)
Do this way: It might solve your problem:
public void Load(String fileName) throws FileNotFoundException{
BufferedReader r = new BufferedReader (new FileReader(fileName));
Scanner sc = new Scanner(r);
while(sc.hasNextLine()){
while(sc.hasNext()){
String temp =sc.nextLine();
if(temp.startsWith("Add")){
temp = temp.replaceAll("Add ", "");
String[] word = temp.split("\\s", 2);
Add(word[0], word[1]);
}else if(temp.equals("List")){
System.out.println("List");
}
}
}
}