Introduction

  • In this blog, I am going to explain the program for word, character and line count in Java.

Software Requirements

  • Java, Notepad.
Program
  1. import java.io.*;
  2. public class WordCount {
  3. private static void linecount(String fName, BufferedReader in ) throws IOException {
  4. long numChar = 0;
  5. long numLine = 0;
  6. long numWords = 0;
  7. String line;
  8. do {
  9. line = in .readLine();
  10. if (line != null) {
  11. numChar += line.length();
  12. numWords += wordcount(line);
  13. numLine++;
  14. }
  15. } while (line != null);
  16. System.out.println("File Name: " + fName);
  17. System.out.println("Number of characters: " + numChar);
  18. System.out.println("Number of words: " + numWords);
  19. System.out.println("Number of Lines: " + numLine);
  20. }
  21. private static void linecount(String fileName) {
  22. BufferedReader in = null;
  23. try {
  24. FileReader fileReader = new FileReader(fileName); in = new BufferedReader(fileReader);
  25. linecount(fileName, in );
  26. } catch (IOException e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. private static long wordcount(String line) {
  31. long numWords = 0;
  32. int index = 0;
  33. boolean prevWhiteSpace = true;
  34. while (index < line.length()) {
  35. char c = line.charAt(index++);
  36. boolean currWhiteSpace = Character.isWhitespace(c);
  37. if (prevWhiteSpace && !currWhiteSpace) {
  38. numWords++;
  39. }
  40. prevWhiteSpace = currWhiteSpace;
  41. }
  42. return numWords;
  43. }
  44. public static void main(String[] args) {
  45. long numChar = 0;
  46. long numLine = 0;
  47. String line;
  48. try {
  49. if (args.length == 0) {
  50. BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  51. line = in .readLine();
  52. numChar = line.length();
  53. if (numChar != 0) {
  54. numLine = 1;
  55. }
  56. System.out.println("Number of characters: " + numChar);
  57. System.out.println("Number of words: " + wordcount(line));
  58. System.out.println("Number of lines: " + numLine);
  59. } else {
  60. for (int i = 0; i < args.length; i++) {
  61. linecount(args[i]);
  62. }
  63. }
  64. } catch (IOException e) {
  65. e.printStackTrace();
  66. }
  67. }
  68. }
Output
Output

Comments

Join the conversation! Your thoughts help the community grow.