2017-02-19 70 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之前直接出现,它将被省略。 –