我有一个简单的问题。我正在尝试读取使用该程序写入桌面的外部文件。我可以正确搜索匹配项,但是当我找不到匹配项时,我希望它打印“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;
最佳答案
我注意到你的循环将为每条匹配的行打印出“Contact was FOUND”部分(我假设是因为可能不止一个)...既然是这种情况,你需要使用另一个标志来确定是否有任何匹配,然后如果没有匹配则输出。
在 while 循环中尝试这个:
// Loop through each line, put the line into our line variable.
boolean noMatches = true;
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);
noMatches = false;
}
}
// Close the file after done searching
bf.close();
if ( noMatches ) {
System.out.println( "NO MATCH FOUND.\n" );
}
关于java - 如何在扫描外部文件匹配后仅打印一次 "NO MATCH FOUND"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15317935/