【发布时间】:2013-08-16 13:23:37
【问题描述】:
这应该计算文件中的行数、单词数和字符数。
但它不起作用。从输出中它只显示0。
代码:
public static void main(String[] args) throws IOException {
int ch;
boolean prev = true;
//counters
int charsCount = 0;
int wordsCount = 0;
int linesCount = 0;
Scanner in = null;
File selectedFile = null;
JFileChooser chooser = new JFileChooser();
// choose file
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
selectedFile = chooser.getSelectedFile();
in = new Scanner(selectedFile);
}
// count the characters of the file till the end
while(in.hasNext()) {
ch = in.next().charAt(0);
if (ch != ' ') ++charsCount;
if (!prev && ch == ' ') ++wordsCount;
// don't count if previous char is space
if (ch == ' ')
prev = true;
else
prev = false;
if (ch == '\n') ++linesCount;
}
//display the count of characters, words, and lines
charsCount -= linesCount * 2;
wordsCount += linesCount;
System.out.println("# of chars: " + charsCount);
System.out.println("# of words: " + wordsCount);
System.out.println("# of lines: " + linesCount);
in.close();
}
我不明白发生了什么。 有什么建议吗?
【问题讨论】:
-
charsCount、wordsCount和linesCount是否显示 0?还是仅对其中一个显示 0? -
请注意,
while循环内的ch永远不会等于' '或'\n'。扫描程序的默认分隔符是为Character.isWhitespace返回 true 的字符。因此,hasNext方法将跳过该类别下的所有字符。 -
@Joffutt 它显示每个
0