2017-02-19 8 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)1文字または2文字にすることができます。b)EOFの直前に表示される場合は省略されます。 –

関連する問題