2017-02-19 93 views
0

該方法返回一個數組,計算文檔中的行數,單詞和字符數。通過測試文件運行後,我仍然收到一些錯誤。計數單詞,字符和行數

public static int[] wc(Reader in) throws IOException { 

    int data = in.read();  
    int charcounter = 0; 
    int linecounter = 0; 
    int wordcounter = 0; 
    boolean previouswhitespace = false; 

    while (data != -1){ 

     if (((char) data == '\n')){ 
      linecounter++; 
     } 
     if (!(Character.isWhitespace((char) data))){ 
      charcounter++; 
       if ((previouswhitespace == true) || (wordcounter == 0)){ 
        previouswhitespace = false; 
        wordcounter++; 
       } 
     } 
     else if ((Character.isWhitespace((char) data))){ 
      previouswhitespace = true; 
     } 
     data = in.read(); 
    } 
    int[] array = {linecounter, wordcounter, charcounter};  
    return array; 
} 
+0

''\ n''不是平臺無關的換行符 –

+1

什麼錯誤?張貼在問題上。 –

+1

另外,我敢肯定,將int數據轉換爲char不是執行字符解碼操作的正確方法。有很多可能的讀者和文件流,這會更好。 –

回答

0
//To choose the file 
    JFileChooser chooser = new JFileChooser(); 
    chooser.showOpenDialog(null); 
    File file = chooser.getSelectedFile(); 
    String file_path = file.getAbsolutePath(); 

    char[] c; 
    String [] words; 
    int charCounter = 0 ,wordsCounter = 0, lineCounter = 0; 
    //try and catch for the BufferedReader 
    try{ 
     String line; 
     BufferedReader reader = new BufferedReader(new FileReader(file_path)); 
     while((line = reader.readLine()) !=null){ 


     c = line.replace(" ","").toCharArray(); 
     charCounter+=c.length;  
     words = line.split(" "); 
     wordsCounter+=words.length; 
     lineCounter++; 
     } 

    }catch(Exception e){ 
     // Handle the Exception 
    } 

    int array[] = {charCounter , wordsCounter, lineCounter}; 

希望這是幫助您!

+0

注意:由於BufferedReader不返回換行符,因此您無法在此計算它們。 a)它們可以是一個或兩個字符b)如果在EOF之前直接出現,它將被省略。 –