扫描外部文件进行匹配后,如何只打印一次“NO MATCH FOUND”?

时间:2013-03-10 01:32:29

标签: java

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

1 个答案:

答案 0 :(得分:1)

我注意到你的循环将为匹配的EACH行打印出“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" );
    }