Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
计算java程序文件中的字数_Java - Fatal编程技术网

计算java程序文件中的字数

计算java程序文件中的字数,java,Java,我正在编写一个简单的代码,用java计算txt文件中有多少单词。它不工作,因为它有一个“无接触异常”。你能帮我修一下吗?谢谢大家! public class Nr_Fjaleve { public static void main(String args[]) throws FileNotFoundException { Scanner input = new Scanner(new File("teksti.txt")); PrintStream output = new P

我正在编写一个简单的代码,用java计算txt文件中有多少单词。它不工作,因为它有一个“无接触异常”。你能帮我修一下吗?谢谢大家!

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);
}

}

您正在查找
hasNextLine
,但随后只检索
next

因此,只需将代码更改为:

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

我看了一下你的问题,马上找到了解决办法。 为了尽可能地提供帮助,我想给出一种可能的方法(我个人会使用),这种方法更具可读性,可以在Java8Lambda环境中使用

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);
    }

}

希望这能有所帮助。

它找不到的元素是什么?java.util.NoSuchElementException在java.util.Scanner.throwFor(Scanner.java:862)在java.util.Scanner.next(Scanner.java:1371)在Nr_Fjaleve.main(Nr_Fjaleve.java:13)中的线程“main”中的异常附加到构建器后会丢失所有空格字符。然后将连接映射到长度并对(单个)值求和,得到另一个完整的结果。为什么要使用一个简单循环工作得很好的流呢?我编辑了我的代码,并添加了空格字符。我是一个通常更喜欢使用流的人,因为您拥有灵活的可能性。我能看出你处理问题的直接方法。谢谢你的反馈。