(Counting characters, words, and lines in a file) Write a program that will coun
ID: 3622113 • Letter: #
Question
(Counting characters, words, and lines in a file) Write a program that will count the number of characters (excluding control characters ' ' and ' '), words, and lines, in a file. Words are separated by spaces, tabs, carriage return (' '), or line-feed (' ') characters. The file name should be passed as a command-line argument, as shown in Figure 9.21 (in the book). (Command-line arguments are given in Eclipse by going to the Run menu, Run Configurations... option, and then going to the Arguments tab, Program arguments: section.)Explanation / Answer
import java.util.*; import java.io.*; import java.lang.*; class Count { public static void main(String[] arg) throws Exception { int totalchars = 0, totalwords = 0,totallines = 0; String input; StringTokenizer str; BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter a filename : "); input = buffer.readLine(); buffer = new BufferedReader(new FileReader(input)); while((input=buffer.readLine())!=null) { totallines++; str=new StringTokenizer(input," ,;:."); while(str.hasMoreTokens()) { totalwords++; input=str.nextToken(); totalchars+=input.length(); } } System.out.println("Total Character Count is "+ totalchars); System.out.println("Total Word Count is "+ totalwords); System.out.println("Total Line Count : "+ totallines); buffer.close(); } } I hope this will helps to You !
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.