Question
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
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:
Exercise12_13
fix code:
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) { characterCount+=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:" +characterCount); } }
Remarks and hints
Checking output
Your standard output is not what was expected.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started