计算单词,字符和行

时间:2017-02-19 21:03:23

标签: java

该方法是返回一个数组,计算文档中的行数,单词数和字符数。在通过测试文件运行后,我仍然收到一些错误。

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;
}

1 个答案:

答案 0 :(得分: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};

希望这对你有帮助!