java - 如何在扫描外部文件匹配后仅打印一次 "NO MATCH FOUND"?

标签 java

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

相关文章:

java - 使用 xml 文件验证 struts 不起作用

java - 使用 Byte Buddy 对带有强制转换的参数调用方法

java - 如果我只想测试 JdbcTemplate 代码,@DataJpaTest 的等效项是什么?

java - 如何仅在某个配置文件处于 Activity 状态时验证配置属性?

java - 在 RESTful 服务 Java 中实现模板方法设计模式

java - Spring,SockJS - WebSocket 握手期间出错 : Unexpected response code 400

java - "an Arbitrary Object of a Particular Type"在 Java 8 中意味着什么?

java - 如何在android中动态附加字符串并添加到requesturl?

java - 实现死锁条件

java - 绘图应用程序 - 将某些功能添加到 onCreateView 时出错