0

.txt ファイル内の文字列の数をカウントする単純なスキャナーを作成しました。各文字列は nextLine にあります。20,000 を超える文字列があっても、297 という数字が表示されるたびに、カウントが間違っています。.txt ファイルは、私がコーディングした別のプログラムによって作成されたもので、Web サイトからリンクを取得し、FileWriter および BufferedWriter を使用してそれらを .txt ファイルに保存します。何が間違っている可能性がありますか?

public class Counter {

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

    Scanner scanner = new Scanner(new File("/Users/myName/Desktop/test.txt"));
    String string = scanner.next();
    int count = 0;

    while (scanner.hasNextLine()) {
        string = scanner.next();
        count++;
        System.out.println(count);
    }           
 }
}

編集: 文字列の例:

yahoo.com
google.com
etc.
4

4 に答える 4

0

これを試して:

public class Counter {

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

    Scanner scanner = new Scanner(new File("/Users/myName/Desktop/test.txt"));
    int count = 0;

    while (scanner.hasNextLine()) {
        scanner.nextLine();
        count++;
        System.out.println(count);
    }           
 }
}

あなたはこれについてどのような答えを得ていますか?

于 2013-10-13T19:15:55.497 に答える
0

デフォルトでは、空白の区切り文字がスキャナーに使用されますが、この場合、区切り文字として \n 文字を使用する必要がありますか? これに使えますScanner.useDelimiter("\n");

于 2013-10-13T19:16:39.210 に答える
0

これを試してください。 nextLine を使用すると、解析がより正確になります

public class Counter {

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

        Scanner scanner = new Scanner(new File("/Users/myName/Desktop/test.txt"));
        String string = scanner.next();
        int count = 0;

        while (scanner.hasNextLine()) {
            string = scanner.nextLine();
            count += string.split(" ").length;
            System.out.println(count);
        }           
     }
    }
于 2013-10-13T19:10:55.757 に答える