2016-11-26 232 views
1

我在編寫一個程序,它通過命令行輸入文本文件,然後打印出文本文件中的單詞數。我已經花了大約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之間的區別是什麼,所以我嘗試使用兩者中的對象。我確信這是一個顯而易見的問題,我看不到它。我在這裏閱讀了很多類似的帖子,這是我的一些代碼的來源。

我已經得到程序編譯以前,但然後它凍結在命令提示符下。

回答

1

java.nio是新的和改進的java.io版本。您可以使用這個任務。我在命令行測試了下面的代碼,它似乎工作正常。在try塊中解決了「找不到符號」錯誤消息。我認爲你通過實例化一個名爲file的對象File兩次使編譯器感到困惑。正如@dammina回答的那樣,您確實需要將input.next();添加到掃描器的while循環才能繼續下一個單詞。

import java.io.File; 
import java.io.IOException; 
import java.util.Scanner; 

public class WordCounter { 

    private static Scanner input; 

    public static void main(String[] args) { 

     if(args.length == 0) { 
      System.out.println("File name not specified."); 
      System.exit(1); 
     } 

     try { 
      File file = new File(args[0]); 
      input = new Scanner(file); 
     } catch (IOException ioException) { 
      System.err.println("Cannot open file."); 
      System.exit(1); 
     } 

     int total = 0; 
     while (input.hasNext()) { 
      total += 1; 
      input.next(); 
     } 

     System.out.printf("The total number of words without duplication is: %d", total); 

     input.close(); 
    } 

} 
+0

我明白了。謝謝!我試圖實例化文件對象兩次,並讓我的while循環在文本文件的第一個單詞上永遠運行。 – presence

1

您的代碼幾乎是正確的。事情是在你指定的終止條件如下while循環,

while (input.hasNext()) //同時有更多的閱讀

但是因爲你只是增加了計數,而移動到下一個單詞的計數只是增加通過總是數第一個字。爲了使它工作,只需將input.next()添加到循環中,以便在每次迭代中移動到下一個單詞。

while (input.hasNext()) // while there is more to read 
{ 
total += 1; 
input.next(); 
} 
+0

啊啊非常感謝你!你爲我節省了很多時間。 – presence

+0

@presence如果能幫到你,請你注意這個:-) – dammina

相關問題