Chapter 12 Exercise 13, Introduction to Java Programming , Tenth Edition Y. Dani
ID: 3810845 • Letter: C
Question
Chapter 12 Exercise 13, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.
Please include comments in your source code.
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 in Figure 12.13.
FIGURE 12.13 The program displays the number of characters, words, and lines in the given
file.
Command prompt c exercise java Exercise 12-13 Loan java File Loan. java has 1919 characters 210 words T1 lines c exercise DIXExplanation / Answer
package Q
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class A {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Invalid arguments.");
System.out.println("Usage: java Q.A filename");
System.exit(1);
}
File filename = new File(args[0]);
if (!filename.exists()) {
System.out.println(filename + " does not exist.");
System.exit(2);
}
int characters = 0;
int words = 0;
int lines = 0;
try {
Scanner input = new Scanner(filename);
while (input.hasNext()) {
String s = input.nextLine();
lines++;
characters += s.length();
String[] split = s.split(" ");
for (String word : split) {
words++;
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
System.out.println("Characters: " + characters);
System.out.println("Words: " + words);
System.out.println("Lines: " + lines);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.