我正在尝试在文本文件中找到关键字,如果找到则返回该句子。如果找不到关键字,我想调用Writer方法。但由于某种原因,Writer方法总是运行。
需要更改哪些内容才能确保仅在找不到关键字时调用writer方法?
这是我的代码
private static HashMap<String, String[]> populateSynonymMap() {
responses.put("professor", new String[]{"instructor", "teacher", "mentor"});
responses.put("book", new String[]{"script", "text", "portfolio"});
responses.put("office", new String[]{"room", "post", "place"});
responses.put("day", new String[]{"time", "date"});
responses.put("asssignment", new String[]{"homework", "current assignment "});
responses.put("major", new String[]{"discipline", "focus"," study"});
return responses;
}
这是我的主要方法和Writer方法
public static void main(String args[]) throws ParseException, IOException {
/* Initialization */
HashMap<String, String[]> synonymMap = new HashMap<String, String[]>();
synonymMap= populateSynonymMap(); //populate the map
Scanner in = new Scanner(System.in);
Scanner scanner = new Scanner(System.in);
String input = null;
System.out.println("Welcome To DataBase ");
System.out.println("What would you like to know?");
System.out.print("> ");
input = scanner.nextLine().toLowerCase();
String[] inputs = input.split(" ");
boolean found = false;
for(String ing : inputs){ //iterate over each word of the sentence.
for (Map.Entry<String, String[]> entry : synonymMap.entrySet()) {
String key = entry.getKey();
String[] value = entry.getValue();
if (key.equals(ing) || Arrays.asList(value).contains(ing)) {
found = true;
parseFile(entry.getKey());
System.out.println(" Would you like to update this information ? ");
String yellow = in.nextLine();
if (yellow.equals("yes")) {
removedata(entry.getKey());
}
if (yellow.equals("no")) {
System.out.println("Have a good day");
break;
}
break;
//System.out.println("Have a good day!");
// break;
}
}
if(found){
Writer();
}
}
}
}
public static void Writer() {
boolean endofloop = false;
Scanner Keyboard = new Scanner(System.in);
Scanner input = new Scanner(System.in);
File file = new File("data.txt");
try (BufferedWriter wr = new BufferedWriter(new FileWriter(
file.getAbsoluteFile(), true))) { // Creates a writer object
// called wr
// file.getabsolutefile
// takes the filename and
// keeps on storing the old
System.out.println("I do not know, Perhaps you wanna help me learn?"); // data
while ((Keyboard.hasNext())) {
String lines = Keyboard.nextLine();
System.out.print(" is this correct ? ");
String go = input.nextLine();
if (go.equals("no")) {
System.out.println("enter what you want to teach me");
lines = Keyboard.nextLine();
System.out.print(" is this correct ? ");
go = input.nextLine();
}
if (go.equals("yes")) {
wr.write(lines);
wr.write("\n");
wr.newLine();
wr.close();
}
System.out.println("Thankk you");
break;
}
} catch (IOException e) {
System.out.println(" cannot write to file " + file.toString());
}
}
答案 0 :(得分:0)
如果您想在未找到的情况下调用编写器,则必须使用:
if (!found) writer();
你的休息只是终止内循环,你可能想要添加一个
if (found) break;
也可以终止外部循环(你没有说这是否是必需的)。