【发布时间】:2015-10-28 19:24:30
【问题描述】:
我不熟悉从文件中读取文本。 我有一个任务,我需要打印文件中的单词数量。
我在 Mac OS 上使用以 .rtf 结尾的 TextEdit
当我运行以下程序时,即使文档为空,我也会得到输出 5。当我添加单词时,计数不会正确增加。
谢谢。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Analyze{
public static void main(String[] args) throws FileNotFoundException{
Scanner console = new Scanner(System.in);
int words = 0;
System.out.println("This is a word counter");
System.out.println("File name");
String filename = console.next();
File name = new File(filename);
Scanner int2 = new Scanner(name);
while (int2.hasNext()) {
String temp = int2.next();
words++;
}
System.out.println(words);
}
}
【问题讨论】: