Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Put Your Data To Work 52 Tips And Techniques For Effectively Managing Your Database

Authors: Wes Trochlil

1st Edition

0880343079, 978-0880343077

More Books

Students also viewed these Databases questions