-1

ファイルにキーワード「ERROR」が見つからない場合は、「Nothing Found」を一度出力します。このコードは各行をスキャンし、各行の出力を出力します。しかし、「ERROR」が複数の行で見つかった場合は、すべての「エラーが見つかりました。

どんな助けでも大歓迎です!

 import java.io.File;
 import java.io.FileNotFoundException;
 import java.util.Scanner;


    public class Scan {

public static void main(String[] args) throws FileNotFoundException {


    Scanner s = new Scanner(new File("Users/home/test.txt"));
    while(s.hasNextLine()){
        //read the file line by line
    String nextLine = s.nextLine();
                //check if the next line contains the key word
        if(nextLine.contains("ERROR"))
        {
                  //whatever you want to do when the keyword is found in the file
            System.out.println("Failed" + " " + nextLine);
        }
        else if(nextLine.contains("Failed!")){
                System.out.println("Not Found");

        }


        }         

    }

}
4

2 に答える 2

2

私が見たところ、このコードはファイルを通過して出力されます。

"Failed" + " " + nextLine

毎回:

nextLine.contains("ERROR")

これは素晴らしいです!問題はここにあります:

else if(nextLine.contains("Failed!")){
            System.out.println("Not Found");

    }

ループごとに、nextLine に文字列 "Failed!" が含まれているかどうかを確認し、"Not Found" を出力します。

そして、あなたはそれを望んでいないと思います。

これを試して:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ErrorScanner
{
    public static void main(String[] args) throws FileNotFoundException 
    {
        Scanner s = new Scanner(new File("Users/home/test.txt"));
        boolean ifError = false;
        while(s.hasNextLine())
        {  
        String nextLine = s.nextLine();       
            if(nextLine.contains("ERROR"))
            {
                System.out.println("Failed" + " " + nextLine);
                ifError = true;
            }
        }     
        if(! ifError)
        {
            System.out.println("Nothing found");
        }
    }
}
于 2013-08-03T05:13:03.057 に答える