1

簡単な質問があります。プログラムでデスクトップに書き込んだ外部ファイルを読み込もうとしています。一致するものを正しく検索できますが、一致するものが見つからない場合は、「NOMATCHFOUND」と出力します。ただし、外部ファイルで一致するものが見つからなかった行ごとに「NOMATCHFOUND」と出力されます。「NOMATCHFOUND」が1回だけ印刷されるように修正するにはどうすればよいですか?

    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

ループが一致する各行の「ContactwasFOUND」部分を出力することに気付きました(複数存在する可能性があるためだと思います)...その場合は、別のフラグを使用して次のかどうかを判断する必要があります。一致するものがあればそれを出力し、一致しない場合は出力します。

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 に答える