JAVA programming through eclipse. This is an introduction class so the code is f
ID: 3597099 • Letter: J
Question
JAVA programming through eclipse. This is an introduction class so the code is fairly simple.
Use a while loop to read from the file but not a sentinel value loop.
Modify the following code 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 meter
CODE TO MODIFY:
public class FeetConversions {
public static void main(String[] args) {
double meters, feet;
Scanner scnr = new Scanner( System.in );
System.out.println( "Enter the length in feet : ");
feet = scnr.nextDouble();
meters = 0.3048 * feet;
System.out.println("The length in meters is : " + meters );
}
}
Explanation / Answer
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
/**
*
* @author Namburi Ramesh
*/
public class FileIO {
public static void main(String[] args) throws FileNotFoundException, IOException{
DecimalFormat df = new DecimalFormat("#.0"); //to format double values to one decimal place
Scanner inFile = new Scanner(new File("feet.txt")); // initialise a input file stream
FileWriter outFile = new FileWriter(new File("meters.txt")); //initialise a output file stream
double feet,meters;
//read from the input file and write to the output file
while(inFile.hasNext()){
feet = inFile.nextDouble();
meters = 0.3048 * feet;
outFile.append(df.format(feet)+" feet = "+df.format(meters)+" meters ");
}
outFile.close();
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.