Part 1: Modify the feet to meters program from week 2 to read from, and write to
ID: 3725471 • Letter: P
Question
Part 1: Modify the feet to meters program from week 2 to read from, and write to a file. The input file should be named “feet.txt” and the output file “meters.txt”.
The input file should contain just double values. The output file should have on each line the feet and meters, formatted to a single decimal. Example of a line in the output file: (assume 5.2 was read from the file)
5.2 feet coverts to 1.6 meters
Part 2: Read names from an input file called “names.txt” and write those names to an output file called “names2.txt”.
The input file should have two strings on each line separated by a space, which are the first then the last name. The output file should have last, first. No need to sort them into alphabetical order. Example:
If the input file contains:
Mary Jones
Juan Garcia
Chris Young
The output file should then contain:
Jones, Mary
Garcia, Juan
Young, Chris
import java.util.*;
public class feet_to_meters {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
double feet, meters;
// input feet
System.out.println("Feet to Meters Conversion Program");
System.out.print("Enter feet: ");
feet = keyboard.nextDouble();
// calculate meters: feet * 0.305
meters = feet * 0.305;
//output meters
System.out.println(feet + " feet is " + meters + " meters");
keyboard.close();
}
}
Explanation / Answer
Please find my implementation for Q1.
Please repost others in separate post.
Please let me know in case of any issue in Q1.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.*;
public class feet_to_meters {
public static void main(String[] args) throws FileNotFoundException {
double feet, meters;
Scanner fileScanner = new Scanner(new File("feet.txt"));
PrintWriter out = new PrintWriter("meters.txt");
while(fileScanner.hasNextDouble()) {
// read feet
feet = fileScanner.nextDouble();
// calculate meters: feet * 0.305
meters = feet * 0.305;
//write meters
out.write(Double.toString(meters));
}
fileScanner.close();
out.close();
System.out.println("Output successfully written in file");
}
}