Week 12 Lab 3 – this Lab is now due Thursday, April 12 Use List and ArrayList to
ID: 3705901 • Letter: W
Question
Week 12 Lab 3 – this Lab is now due Thursday, April 12
Use List and ArrayList to print a file and average the scores in a file, and use Map to create and use a simple English to Spanish dictionary, with possible extra credit to read the dictionary from a file. These exercises are worth 6, 8, and 8 points, plus 6 extra credit points.
Create a PrintFile class that reads a file’s lines into a List using an ArrayList and then prints them out:
· In Atom, Save CopyFile.java As PrintFile.java and change the class name
· Modify main so that it only expects one command line argument, and if it gets a different number prints out this usage message:
Usage: PrintFile filename
· Create a List called list and instantiate it with an ArrayList
· Remove all of the logic related to the output file, it’s not needed in PrintFile; don’t remove the while loop, just change it as below
· In the while loop use add to add the file’s lines to list like in ArrayListDemo (e.g., list.add(line))
· After closing the input file, print the number of lines in the file, and then use a for-each loop to get them from list and print them out, one per line
· Hints: you can either count the number of lines as you are reading them or, after the while loop, the method list.size() returns the number of items in list
This exercise is worth 6 points.
To test this program use this command: java PrintFile PrintFile.java
Show me or our TA your PrintFile program code and have it print PrintFile.java.
Create an AverageScore program to average the scores in a file:
Write a program that reads a text file containing an unknown number of movie review scores. Read the scores as double values and put them into an instance of ArrayList, then compute and print the average movie score.
Create a text file of double values and use it to test your program.
Hints:
You can start with PrintFile.java and reuse its logic up to the point where you print the lines of the file; instead, add the Doubles to the ArrayList and calculate and print their average. Be sure to change the type of List to List.
To convert a String you have read from the input file to a double, use the method Double.parseDouble(yourString)
When you add a double value to an ArrayList Java automatically “wraps” the double as a Double object; when you get an item from an ArrayList Java will “unwrap” the Double to produce a double value. This is called autoboxing and autounboxing.
Be sure that the size of the list is not 0 before calculating the average!!
This exercise is worth 8 points.
Show me or our TA your AverageScore program code and its test output.
Use a Map to write an E2SP class, a simple English-to-Spanish dictionary:
Start with any base program, but be sure to import java.util.*;
Create a Map to hold translations of common English words and phrases to Spanish:
Map e2sp = new HashMap<>();
and put several lower case words and their translations in the Map, like one à uno
Create a Scanner object connected to the keyboard and, in a loop, ask the user what English word or phrase they would like to translate to Spanish – tell them if they just press Enter that will end the translation – that sends in the empty String, and you should use that to end the loop and then print out the entire Map contents
When they enter a word convert it to lower case and check if it is in the Map
If it is, print out that word or phrase and its translation
If it is not, tell them that you do not have a translation for it
For extra credit, have your program read the dictionary entries from a file. The file should have two lines for each word or phrase translation, the first line being the English version and the second one being the Spanish version. Convert both of those to lower case before putting them into the Map.
This exercise is worth 8 points; the extra credit is worth 6 points.
Show me or our TA your E2SP program code and how it works.
import java.io.*;
public class CopyFile // in CopyFile.java in the Sakai Week 12 Source Code folder
{
public static void main(String[] args) // uses program command line arguments
{
if (args.length != 2) {
System.out.println("Usage: CopyFile inputFile outputFile");
System.exit(0);
}
Scanner170 inStream = IO.inFile(args[0]);
if (inStream == IO.inError) {
System.out.println("Error: could not read input file " + args[0]);
System.exit(0);
}
PrintStream outStream = IO.newFile(args[1]); // assure output doesn't exist yet
if (outStream == IO.outError) {
System.out.println("Error: could not create output file " + args[1]);
System.exit(0);
} // could also use IO.exists(args[1]) first to check if output file exists
while (inStream.hasNextLine())
outStream.println(inStream.nextLine());
inStream.close(); // close the input file when done reading from it
outStream.close(); // close the output file when done writing to it
}
}
Explanation / Answer
PrintFile.java
==============
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class PrintFile{
public static void main(String[] args)
{
if (args.length != 1) {
System.out.println("Usage: PrintFile inputFile");
System.exit(0);
}
Scanner inputStream = null;
try{
//input file is assumed to be at the same location as your java file
inputStream = new Scanner(new FileInputStream(PrintFile.class.getResource(args[0]).getPath()));
}catch(Exception e){
System.out.println("Error:Could not read inputfile "+args[0]);
System.exit(0);
}
List<String>fileLineList = new ArrayList<>();
while(inputStream.hasNextLine()){
fileLineList.add(inputStream.nextLine());
}
inputStream.close();
System.out.println("Number of line in the file:"+fileLineList.size());
System.out.println("The content of the file");
for(String line : fileLineList){
System.out.println(line);
}
}
}
Output
======
Number of line in the file:10
The content of the file
Test Line 1
Test Line 2
Test Line 3
Test Line 4
Test Line 5
Test Line 6
Test Line 7
Test Line 8
Test Line 9
Test Line 10
AverageScore.java
==================
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class AverageScore {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: AverageScore inputFile");
System.exit(0);
}
Scanner inputStream = null;
try{
//input file is assumed to be at the same location as your java file
inputStream = new Scanner(new FileInputStream(PrintFile.class.getResource(args[0]).getPath()));
}catch(Exception e){
System.out.println("Error:Could not read inputfile "+args[0]);
System.exit(0);
}
List<Double>fileLineList = new ArrayList<>();
while(inputStream.hasNextLine()){
fileLineList.add(Double.parseDouble(inputStream.nextLine()));
}
inputStream.close();
double avgScore = 0;
for(double score : fileLineList){
avgScore+=score;
}
System.out.println(fileLineList.size()==0?"No review score available in the file!!!":"Average Review Score = "+(avgScore/fileLineList.size()));
}
}
File Content
===========
4.0
5.4
3.7
4.2
4.5
6.7
8.3
9.02
9.9
8.5
Output
======
Average Review Score = 6.422
English2Spanish.java
====================
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class English2Spanish {
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: English2Spanish inputFile");
System.exit(0);
}
Scanner inputStream = null;
try{
//input file is assumed to be at the same location as your java file
inputStream = new Scanner(new FileInputStream(PrintFile.class.getResource(args[0]).getPath()));
}catch(Exception e){
System.out.println("Error:Could not read inputfile "+args[0]);
System.exit(0);
}
Map<String,String>e2sp = new HashMap<>();
while(inputStream.hasNextLine()){
try{
String english = inputStream.nextLine();
String spanish = inputStream.nextLine();
e2sp.put(english.trim().toLowerCase(), spanish.trim().toLowerCase());
}catch(Exception e){
break;
}
}
inputStream.close();
String input=null;
System.out.println("Enter words in english: press enter to exit.");
inputStream = new Scanner(System.in);
while(inputStream.hasNextLine()){
input = inputStream.nextLine().trim().toLowerCase();
if(input.length()==0){
break;
}
if(e2sp.containsKey(input)){
System.out.println("Spanish("+input+")="+e2sp.get(input));
}else{
System.out.println("Sorry no translation is available with me for "+input+". Try with something else");
}
}
inputStream.close();
System.out.println("The contents of the map:");
for(String key : e2sp.keySet()){
System.out.println("Spanish("+key+")="+e2sp.get(key));
}
}
}
Output
======
Enter words in english: press enter to exit.
Good Morning
Spanish(good morning)=buenos días
Good Night
Spanish(good night)=buenas noches
Thank you
Spanish(thank you)=gracias
The contents of the map:
Spanish(good night)=buenas noches
Spanish(good morning)=buenos días
Spanish(hello)=hola
Spanish(thank you)=gracias
Spanish(excuse me)=disculpe
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.