Question: Help with Java Programming. Programming Exercise 12.13 (Count characters, words, and lines in a file) Write a program that will count the number of characters,
Help with Java Programming.
Programming Exercise 12.13
(Count characters, words, and lines in a file) Write a program that will count the number of characters, words, and lines in a file. Words are separated by whitespace characters. The file name should be passed as a command-line argument, as shown below.
c:\exercise>java Exercise12_13 Loan.java File loan.java has 1919 characters 210 words 71 lines
c:\exercise> Class Name to be used in your program: Exercise12_13
After my useless attempts, I tried a few places to look for the solution. I found the exact problem solution on Chegg for a Java Programming textbook: https://www.chegg.com/homework-help/count-characters-words-lines-file-write-program-count-number-chapter-12-problem-13pe-solution-9780133592658-exc
Program:
import java.io.*; import java.util.*; public class Exercise12_13 { public static void main(String[] args) throws Exception { if(args.length != 1) { System.out.println("Command-line argument is missing!"); System.exit(1);; } String fileName = args[0]; File source = new File(fileName); if(!source.exists()) { System.out.println(fileName + "file does not exist!."); System.exit(2);; } Scanner infile = new Scanner(source); String line; int characterCount = 0; int wordsCount = 0; int linesCount = 0; while(infile.hasNextLine()) { line = infile.nextLine(); linesCount++; String[] words = line.split(""); wordsCount += words.length; for(String token : words) { charactersCount+=token.length(); } } System.out.println("Name of the input file:" +fileName); System.out.println("Number of lines in the file:" +linesCount); System.out.println("Number of words in the file:" +wordsCount); System.out.println("Number of characters in the file:" +charactersCount); } }
^ I typed out that program and it returns:
Compiler error: cannot find symbol
charactersCount+=token.length();
^
symbol: variable charactersCount
location: class Exercise12_13
Compiler error: cannot find symbol
System.out.println("Number of characters in the file:" +charactersCount);
^
symbol: variable charactersCount
location: class Exercise12_13
Thank you in advance.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
