问题
我目前正在创建一个程序来读取文件并找到几个变量。我遇到这个问题,更改一个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语句会改变整个输出。它首先出现的唯一原因是确保扫描程序按照我想要的方式进行输入。
不确定为什么while语句中的一个print语句会改变整个输出
因为当语句出现时,您正在使用扫描程序中的令牌。当它被注释掉时,你不是。这不是消耗令牌的打印,而是对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++;
}
不知道你为什么要通过文本三次。但是如果你真的需要,我会在打开下一个之前关闭第一个扫描仪。