Java 来自文件的命令
我试图读取一个文件,并根据文件的每行内容执行命令。 该文件如下所示:Java 来自文件的命令,java,file,java.util.scanner,bufferedreader,Java,File,Java.util.scanner,Bufferedreader,我试图读取一个文件,并根据文件的每行内容执行命令。 该文件如下所示: 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)); Scann
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
我知道问题不在报纸上。问题在上面的**中。关于如何解决这个问题有什么建议吗?试试这个
if(temp.startsWith("Add")){
String word = sc.next().toLowerCase().replaceFirst("All", "");
String def = sc.nextLine().toLowerCase().replaceFirst("All", "");;
Add(word, def);
}
你需要找到一种从字符串中去掉“Add”的方法,如果sc.next.toLowerCase().equals(“Add”);skip和word等于sc.next,你可以做另一个条件。这应该会给你想要的结果。我们还能看到你的print方法吗?@chrisedwards the Add()将单词及其定义发送到二进制搜索树和list()中按字母顺序打印树。
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");
}
}
}
}