Problem 1. (Line, Word, and Character Counts) Write a program WC that prints the
ID: 645778 • Letter: P
Question
Problem 1. (Line, Word, and Character Counts) Write a program WC that prints the
number of lines, words, and characters in the input read from standard input. The
program should take an optional command-line argument, which can be -l, -w, or -c.
If the argument is specified, the program should print only the line, word, or character
count, and if the argument is not specified, the program should print all the counts. If
the argument is not valid (eg, -z), the program should print Unknown argument: -z. Hint:
Use the trim(), split(), and length() methods from String.
$ java WC < lorem . txt
3 161 1092
$ java WC -w < lorem . txt
161
$ java WC -z < lorem . txt
Unknown argument : -z
Explanation / Answer
import java.util.*; import java.io.*; public class TextFileInfoPrinter { public static void main(String[]args) throws FileNotFoundException { Scanner console = new Scanner(System.in); System.out.println("File to be read: "); String inputFile = console.next(); File file = new File(inputFile); Scanner in = new Scanner(file); int words = 0; int lines = 0; int chars = 0; while(in.hasNext()) { in.next(); words++; } while(in.hasNextLine()) { in.nextLine(); lines++; } while(in.hasNextByte()) { in.nextByte(); chars++; } System.out.println("Number of lines: " + lines); System.out.println("Number of words: " + words); System.out.println("Number of characters: " + chars); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.