Reputation: 53
import java.io.File;
import java.io.PrintWriter;
public class Hw6Problem004 {
public static void main(String[] args) throws Exception {
{
double j = 120;
for (double i = 40; i >= 31; i--) {
//Create File object for the file
File outFile = new File("temperature_table.text");
//Create the PrintWriter object
PrintWriter pw = new PrintWriter(outFile);
pw.println("celsius \tFahrenheit \t| Fahrenheit \tCelsius");
double cTf = (double) Math.round(celsiusToFahrenheit(i) * 100) / 100;
double decimal = (double) Math
.round(fahrenheitToCelsius(j) * 100) / 100;
pw.println(i + "\t\t" + cTf + "\t\t|" + "\t" + j + "\t" + "\t"
+ decimal);
System.out.println("");
j -= 10;
pw.close();
}
}
}
// • Converts a Celsius value to Fahrenheit
public static double celsiusToFahrenheit(double celsius) {
return (9.0 / 5) * celsius + 32;
}
// Converts a Fahrenheit value to Celsius
public static double fahrenheitToCelsius(double fahrenheit) {
return (5.0 / 9) * (fahrenheit - 32);
}
}
This is what I am getting:
// celsius Fahrenheit | Fahrenheit Celsius
// 31.0 87.8 | 30.0 -1.11
I need to get this:
// celsius Fahrenheit | Fahrenheit Celsius
// 40.0 104.0 | 120.0 48.89
// 39.0 102.2 | 110.0 43.33
// 38.0 100.4 | 100.0 37.78
// 37.0 98.6 | 90.0 32.22
// 36.0 96.8 | 80.0 26.67
// 35.0 95.0 | 70.0 21.11
// 34.0 93.2 | 60.0 15.56
// 33.0 91.4 | 50.0 10.0
// 32.0 89.6 | 40.0 4.44
// 31.0 87.8 | 30.0 -1.11
I am getting only the last row of my table on the text file. I need to show the whole output on my text file.
Upvotes: 0
Views: 258
Reputation: 393771
You should open and close the PrintWriter outside the loop :
File outFile = new File("temperature_table.text");
PrintWriter pw = new PrintWriter(outFile);
for (double i = 40; i >= 31; i--) {
pw.println("celsius \tFahrenheit \t| Fahrenheit \tCelsius");
double cTf = (double) Math.round(celsiusToFahrenheit(i) * 100) / 100;
double decimal = (double) Math
.round(fahrenheitToCelsius(j) * 100) / 100;
pw.println(i + "\t\t" + cTf + "\t\t|" + "\t" + j + "\t" + "\t"
+ decimal);
System.out.println("");
j -= 10;
}
pw.close();
Currently, in each iteration of the loop you are overwriting the output file.
Upvotes: 1