1

我有一个快速的问题。我正在尝试使用该程序读取我写入桌面的外部文件。我可以正确搜索匹配项,但是当我找不到匹配项时,我希望它打印“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;
4

1 回答 1

1

我注意到您的循环将为匹配的每一行打印出“找到联系人”部分(我假设因为可能不止一个)...既然是这种情况,您需要使用另一个标志来确定是否进行了任何匹配,如果没有匹配则输出。

在你的 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" );
    }
于 2013-03-10T01:40:28.803 回答