计算文件java程序中的单词

时间:2018-06-05 11:52:16

标签: java

我正在编写一个简单的代码来计算带有java的txt文件中有多少单词。它没有工作,因为它有一个" noSuchElementException"。你能帮我解决一下吗?谢谢!

public class Nr_Fjaleve {

public static void main(String args[]) throws FileNotFoundException {
    Scanner input = new Scanner(new File("teksti.txt"));
    PrintStream output = new PrintStream(new File("countwords.txt"));
    int count = 0;
    while (input.hasNextLine()) {
        String fjala = input.next();
        count++;
    }
    output.print(count);
}

}

2 个答案:

答案 0 :(得分:3)

您正在寻找hasNextLine,但之后只检索next

只需将代码更改为:

while (input.hasNext()) {
    String fjala = input.next();
    count++;
}

答案 1 :(得分:-1)

我看了你的问题并立即找到了解决方案。 为了尽可能地提供帮助,我想提供一种可行的方法(我个人会使用),它更具可读性,可以在Java 8 Lambda环境中使用。

public class Nr_Fjaleve {

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

        Scanner input = new Scanner(new File("teksti.txt"));
        PrintStream output = new PrintStream(new File("countwords.txt"));

        final int count = Stream.of(input).map(i -> {
            try {
                final StringBuilder builder = new StringBuilder();

                // Your original problem was here as you called the #next method 
                // while iterating over it with the #hasNext method. This will make the counting go wrong.
                while (i.hasNextLine()) {
                    builder.append(i.nextLine());
                }
                return builder;
            } finally {
                i.close();
            }
        }).mapToInt(StringBuilder::length).sum();

        output.print(count);
    }

}

希望这有任何帮助。