Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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); } }

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote