Reputation:
I am having an issue. I want to search a text file for multiple matching keywords from a String []
. I want to output only the sentence that contains one or more of these matching keywords.
So String[] keywords = { "going", "What book", "not going ","office", "okay"};
If a file called data.txt
contains the sentence " I am going to the office at 6".And the user enters "going and office" I want to print this sentence to console. But as of right now I can only search the file for only one matching keyword. Can someone guide me in the direction to finding multiple keywords in a file.
So here is my method to search the text
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;
}
}
}
and here is my main method
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!");
}
}
Upvotes: 0
Views: 2959
Reputation:
Just use a loop. Either this way, if one match is sufficient:
String line = ...;
String[] search = new String[]{...};
boolean match = false;
for(int i = 0 ; i < search.length && !match; i++)
match = line.contains(search[i]);
or, if all strings must be part of line:
String line = ...
String[] search = new String[]{...};
boolean match = true;
for(int i = 0 ; i < search.length && match ; i++)
match = line.contains(search[i]);
Upvotes: 1