In: Computer Science
In Java:
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
Please find the code for the following:
Code:
import java.io.*;
import java.util.*;
class Exercise_12_13 {
/** Main method */
public static void main(String[] args) throws
Exception
{
//Creating an object of Class File by calling the constructor
//With a parameter named args[0] which is th file name.
File file = new
File(args[0]);
int characters = 0, words = 0,
lines = 0;
//Here, we are using Java Scanner class for opening and reading a file.
// Create an
object of Scanner class by calling the constructor with the file
parameter which we created
Scanner s1 = new
Scanner(file);
Scanner s2 = new Scanner(file);
//Iterating over all the lines and calculating the number of
lines as well as the characters here.
while
(s1.hasNext())
{
lines++; //Increment the line count
String line = s1.nextLine();
characters += line.length(); //Increment the
characters count
}
//Iterating over all the lines and then calculating the number of
wods present in entire file.
while
(s2.hasNext())
{
String line = s2.next();
words++;
}
//Printing the result as
provided in the sample output
System.out.println("File " +
args[0] + " has");
System.out.println(characters + "
characters");
System.out.println(words + "
words");
System.out.println(lines + "
lines");
}
}
Please check the
compiled program and its output for your reference:
Output:
Since the output of the file Loan.java varies from your file
Loan.java. The result may vary but still is appropriate to the file
which is being taken as a command line parameter for this class.
please notice that.[I also outputted the Loan.java file for your
understanding]
(I believe that I made the code simple and understandable. If you
still have any query, Feel free to drop me a comment)
Hope this Helps!!!
Please upvote as well, If you got the answer?
If not please comment, I will Help you with that...