为什么一个 println 语句会改变我的代码的整个输出?

Why does one println statement change the entire output of my code?

问题

我目前正在创建一个程序来读取文件并查找几个变量。我正在 运行 解决这个问题,其中更改一个 println 会更改我的代码的整个输出。我以前从未 运行 进入过这个,我不确定这是日食错误还是我的错误?

我的代码

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class FileAnalyzer {
    public static void main(String args[]) throws IOException {
        Scanner input = new Scanner(System.in);
        String fileName;
        int words = 0, letters = 0, blanks = 0, digits = 0, miscChars = 0, lines = 0;

        System.out.print("Please enter the file path of a .txt file: ");
        fileName = input.nextLine();

        File text = new File(fileName);
        //System.out.println(text.exists());

        Scanner word = new Scanner(text);
        while(word.hasNext()) {
            //System.out.println(word.next());
            words++;
        }
        word.close();

        Scanner letter = new Scanner(text);
        while(letter.hasNext()) {
            String currentWord = letter.next().toLowerCase();
            for(int i = 0; i < currentWord.length(); i++) {
                if(Character.isLetter(currentWord.charAt(i))) {
                    letters++;
                }
            }
        }
        letter.close();

        Scanner blank = new Scanner(text);
        while(blank.hasNextLine()) {
            String currentWord = blank.nextLine();
            for(int j = 0; j < currentWord.length(); j++) {
                if (currentWord.charAt(j) == ' ') {
                    blanks++;
                }
            }
        }
        blank.close();

        System.out.println("Words: " + words);
        System.out.println("Letters: " + letters);
        System.out.println("Blanks: " + blanks);


    }
}

不过

只需更改第一个 Scanner 实例中的System.out.println(word.next()) 即可更改整个输出。如果我把它留在里面,我会在底部看到三个打印语句以及我要查找的内容。如果我删除它,因为我不想在文件中打印每个单词,它在控制台中显示为空。不确定为什么 while 语句中的一个 print 语句会更改整个 output.The 唯一的原因是它首先存在是为了确保扫描仪按照我想要的方式接收输入。

Not Sure why one print statement within a while statement changes the entire output

因为当语句出现时,您正在使用来自扫描仪的令牌。当它被注释掉时,你不是。消耗令牌的不是打印,而是对 next().

的调用

注释掉后,你的循环是:

while (word.hasNext()) {
    words++;
}

hasNext() 不会修改扫描器的状态,因此 如果它完全进入循环体就永远循环。

如果你想有一行你可以注释掉或不注释掉,把代码改成:

while (word.hasNext()) {
    String next = word.next(); // Consume the word
    System.out.println(next); // Comment this out if you want to
    words++;
}

不确定为什么要将文本浏览三遍。但如果你真的必须这样做,我会先关闭第一个扫描仪,然后再打开下一个。

通过使用 System.out.println(word.next());,由于 next() 方法,您正在循环访问集合中的元素。因此直接调用 next() 将允许您在迭代中移动。

当注释掉//System.out.println(word.next());时,word.hasNext()将导致你永远循环(前提是有一个词),因为你将无法移动到下一个标记。

下面的代码片段将帮助您获得想要的结果

while(word.hasNext()){
   word.next();
   words++;
}