Counting lines, words by Java.

I’d like to write a program that will call the file to the main method, but I feel confused about counting lines, words and characters.

Could someone help me to solve this problem?

Thank you very much.

2 個解答

評分
  • 9 年前
    最佳解答

    請參考我的做法

    import java.io.*;

    import java.util.*;

    public class Y7159 {

    public static void main(String[] args) {

    String s = "temp.txt";

    if (args.length != 0) s = args[0];

    Scanner scan = null;

    try {

    scan = new Scanner(new File(s));

    } catch (Exception e) {

    e.printStackTrace();

    }

    int lineCount = 0; // number of lines

    int wordCount = 0; // number of words

    int charCount = 0; // number of characters

    while (scan.hasNextLine()) {

    s = scan.nextLine();

    lineCount++; // add to lineCount when reading a line

    String[] ary = s.split("\\W"); // simply using non-word character seperation

    wordCount += ary.length; // add to wordCount the number of words in a line

    for (String s2 : ary) {

    charCount += s2.length(); // add to charCount the number of characters in a word

    }

    }

    System.out.println("Line number: " + lineCount);

    System.out.println("Word number: " + wordCount);

    System.out.println("Character number: " + charCount);

    }

    }

  • 9 年前

    You might post your sample codes here so that we can help you out.

還有問題?馬上發問,尋求解答。