【发布时间】:2019-04-01 17:21:58
【问题描述】:
问题
我目前正在创建一个程序来读取文件并查找几个变量。我遇到了这个问题,改变一个 println 会改变我的代码的整个输出。我以前从未遇到过这种情况,不确定这是 Eclipse 错误还是我的错误?
我的代码
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 语句中的一个打印语句会更改整个输出。它首先存在的唯一原因是确保扫描仪以我想要的方式接收输入。
【问题讨论】:
标签: java file file-io java.util.scanner