Java Code. Please help me write the code... Test file: Write a program WordLengt
ID: 3791883 • Letter: J
Question
Java Code. Please help me write the code...
Test file:
Explanation / Answer
WordLengths.java
--------------------------------
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;
public class WordLengths {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: Please input two files, first one is for input and second one is for output.");
System.out.println("java WordLengths romeo.txt counts.txt.");
}
try {
System.out.println("input file: " + args[0]);
System.out.println("output file: " + args[1]);
File inputFile = new File(args[0]);
File outputFile = new File(args[1]);
HashMap<Integer, Integer> wordLengths = new HashMap<Integer, Integer>();
Scanner sc = new Scanner(inputFile);
String word = "";
Integer number = 0;
Integer length = 0;
while (sc.hasNext()) {
word = sc.next();
if(word.trim().isEmpty())
continue;
/*
for removing any type of punctuation we use \W.
it preserves only alphabets, digits and alphanumarics.
*/
// System.out.println(word + " - "+word.replaceAll("\W", ""));
word = word.replaceAll("\W", "");
length = word.length();
if (length >= 12) {
length = 12;
}
number = wordLengths.get(length);
if (null == number) {
number = 1;
} else {
number++;
}
wordLengths.put(length, number);
}
sc.close();
//printing analysis
StringBuilder output = new StringBuilder();
output.append("Length ");
for(int i=1; i<=11; i++) {
// here %5s is for printing spaces with right justification alignment
output.append(String.format("%5s", i+""));
}
output.append(String.format("%5s", "12+"));
output.append(" ");
output.append("Number ");
for(int i=1; i<=12; i++) {
output.append(String.format("%5s", wordLengths.get(i)+""));
}
//writing output to console
System.out.println(output.toString());
//writing output to counts.txt
FileWriter fw = new FileWriter(outputFile);
fw.write(output.toString());
fw.flush();
fw.close();
} catch (IOException e) {
System.out.println("Please give proper file names.");
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
Console output:
----------------------
java WordLengths remeo.txt counts.txt
input file: romeo.txt
output file: counts.txt
Length 1 2 3 4 5 6 7 8 9 10 11 12+
Number 295 1002 1298 1406 919 473 411 254 109 61 21 26
counts.txt:
----------------------
Length 1 2 3 4 5 6 7 8 9 10 11 12+
Number 295 1002 1298 1406 919 473 411 254 109 61 21 26
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.