count characters, words and lines in file

后端 未结 8 1741
离开以前
离开以前 2020-12-18 16:47

This should count number of lines, words and characters into file.

But it doesn\'t work. From output it shows only 0.

Code:

8条回答
  •  無奈伤痛
    2020-12-18 17:50

    Maybe my code will help you...everything work correct

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Scanner;
    import java.util.StringTokenizer;
    
    public class LineWordChar {
        public static void main(String[] args) throws IOException {
            // Convert our text file to string
        String text = new Scanner( new File("way to your file"), "UTF-8" ).useDelimiter("\\A").next();
        BufferedReader bf=new BufferedReader(new FileReader("way to your file"));
        String lines="";
        int linesi=0;
        int words=0;
        int chars=0;
        String s="";
        // while next lines are present in file int linesi will add 1
            while ((lines=bf.readLine())!=null){
            linesi++;}
        // Tokenizer separate our big string "Text" to little string and count them
        StringTokenizer st=new StringTokenizer(text);
         while (st.hasMoreTokens()){
            `enter code here`  s = st.nextToken();
              words++;
        // We take every word during separation and count number of char in this words    
              for (int i = 0; i < s.length(); i++) {
                  chars++;}
            }
         System.out.println("Number of lines: "+linesi);
         System.out.println("Number of words: "+words);
         System.out.print("Number of chars: "+chars);
     }
    }
    

提交回复
热议问题