我在編寫一個程序,它通過命令行輸入文本文件,然後打印出文本文件中的單詞數。我已經花了大約5個小時了。我正在使用java介紹一個類。在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之間的區別是什麼,所以我嘗試使用兩者中的對象。我確信這是一個顯而易見的問題,我看不到它。我在這裏閱讀了很多類似的帖子,這是我的一些代碼的來源。
我已經得到程序編譯以前,但然後它凍結在命令提示符下。
我明白了。謝謝!我試圖實例化文件對象兩次,並讓我的while循環在文本文件的第一個單詞上永遠運行。 – presence