【发布时间】:2017-04-10 21:22:06
【问题描述】:
我正在尝试编写一个程序,该程序通过命令行输入文本文件,然后打印出文本文件中的字数。我已经在这上面花了大约 5 个小时。我正在学习使用 java 的入门课程。
这是我的代码:
import java.util.*;
import java.io.*;
import java.nio.*;
public class WordCounter
{
private static Scanner input;
public static void main(String[] args)
{
if (0 < args.length) {
String filename = args[0];
File file = new File(filename);
}
openFile();
readRecords();
closeFile();
}
public static void openFile()
{
try
{
input = new Scanner(new File(file));
}
catch (IOException ioException)
{
System.err.println("Cannot open file.");
System.exit(1);
}
}
public static void readRecords()
{
int total = 0;
while (input.hasNext()) // while there is more to read
{
total += 1;
}
System.out.printf("The total number of word without duplication is: %d", total);
}
public static void closeFile()
{
if (input != null)
input.close();
}
}
我尝试过的每一种方法都会出现不同的错误,最一致的错误是文件参数中的“找不到符号”
input = new Scanner(new File(file));
我仍然不完全确定 java.io 和 java.nio 之间的区别是什么,所以我尝试使用两者中的对象。我确定这是一个明显的问题,我只是看不到它。我在这里阅读了很多类似的帖子,这就是我的一些代码的来源。
我之前已经让程序编译,但它在命令提示符下冻结。
【问题讨论】: