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

Files and Classes Any Unix machine has a command called word counter (WC) create

ID: 3627415 • Letter: F

Question

Files and Classes
Any Unix machine has a command called word counter (WC)
create a class called WC.
The class should have:

Constructor
A minimum of 3 methods,namely:
1.numLines(return # of lines).
2.numWords(returns # of words)use string tokenizer/split and count.
3.numChars(return # of Characters)

How to pass arguments to these methods:
numChars()
or numLines(File f)

How to run the program:
java MyWC doit , this command will generate lines,words,and characters.
java MyWc -l doit, this command will generate lines.
java MyWc -w doit,this command will generate words.
java MyWc -l -w doit,this command will generate Lines and Words.
java MYWc -l -c -w doit,this command will generate Lines,words,and characters.

Explanation / Answer

import java.io.*; import java.util.*; class WC { Scanner scan; FileReader fr; public WC(){ try{ fr = new FileReader("sample.txt"); scan = new Scanner(fr); } catch(FileNotFoundException e){ System.out.println("file not found"); } } public int numLines(){ int lines = 0; while(scan.hasNextLine() == true) { scan.nextLine(); lines++; } return lines; } public int numWords() throws FileNotFoundException{ scan.close(); //you have to close and reopen the scanner because it can't reset scan = new Scanner(new FileReader("sample.txt")); int words = 0; while(scan.hasNext() == true) { scan.next(); words++; } return words; } public int numChars()throws FileNotFoundException{ scan.close(); scan = new Scanner(new FileReader("sample.txt")); int chars = 0; String temp; while(scan.hasNextLine() == true) { temp = scan.nextLine(); chars = chars + temp.length(); } return chars; } public static void main(String [] args) throws Exception { WC test = new WC(); int length = args.length; String command = args[0]; for(int i = 1; i
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