繁体   English   中英

计算字,字符和行

[英]Counting words, characters and lines

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

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

希望这对您有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM