簡體   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