我遇到了问题。我想在文本文件中搜索String []
中的多个匹配关键字。我想只输出包含一个或多个匹配关键字的句子。
所以String[] keywords = { "going", "What book", "not going ","office", "okay"};
如果名为data.txt
的文件包含句子“我将在6点去办公室”。用户输入“去办公室”我想将这句话打印到控制台。但截至目前,我只能在文件中搜索一个匹配的关键字。有人可以指导我在文件中找到多个关键字。
所以这是我搜索文本的方法
public static void parseFile(String s) throws FileNotFoundException {
File file = new File("data.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String lineFromFile = scanner.nextLine();
if (lineFromFile.contains(s)) {
// a match!
System.out.println(lineFromFile);
// break;
}
}
}
这是我的主要方法
public static void main(String args[]) throws ParseException,
FileNotFoundException {
String[] keywords = { "going", "What book", "not going ","office", "okay"};
boolean endloop = false;
boolean found = false;
Scanner scanner = new Scanner(System.in);
String input = null;
System.out.println("What's up?");
do {
System.out.print(" - ");
input = scanner.nextLine().toLowerCase();
for (String keyword: keywords) {
if (input.contains(keyword)) {
parseFile(keyword);
}
}
if (!found) {
System.out
.println("I am sorry I do not know");
}
break;
}
while (!input.equalsIgnoreCase("thanks"));
System.out.println(" Have a good day!");
}
}
答案 0 :(得分:1)
只需使用循环。无论如何,如果一个匹配就足够了:
String line = ...;
String[] search = new String[]{...};
boolean match = false;
for(int i = 0 ; i < search.length && !match; i++)
match = line.contains(search[i]);
或者,如果所有字符串必须是行的一部分:
String line = ...
String[] search = new String[]{...};
boolean match = true;
for(int i = 0 ; i < search.length && match ; i++)
match = line.contains(search[i]);