我有一个快速的问题。我正在尝试使用该程序读取我写入桌面的外部文件。我可以正确搜索匹配项,但是当我找不到匹配项时,我希望它打印“NO MATCH FOUND”。但是,它会为在我的外部文件中找不到匹配项的每一行打印“NO MATCH FOUND”。我将如何解决它,所以它只打印一次“NO MATCH FOUND”?
System.out.println("Enter the email "
+ "address to search for: ");
String searchterm = reader.next();
// Open the file as a buffered reader
BufferedReader bf = new BufferedReader(new FileReader(
"/home/damanibrown/Desktop/contactlist.txt"));
// Start a line count and declare a string to hold our current line.
int linecount = 0;
String line;
// Let the user know what we are searching for
System.out.println("Searching for " + searchterm
+ " in file...");
// Loop through each line, put the line into our line variable.
while ((line = bf.readLine()) != null) {
// Increment the count and find the index of the word
linecount++;
int indexfound = line.indexOf(searchterm);
// If greater than -1, means we found a match
if (indexfound > -1) {
System.out.println("Contact was FOUND\n"
+ "Contact " + linecount + ": " + line);
}
}
// Close the file after done searching
bf.close();
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
break;