This program calculates the surface gravities of 9 planets, prints the data to the screen in a formatted table, and is supposed to print only the surfaceGravity values to a file. I'm not sure why my code won't print the calculated surfaceGravity value to the file called gravities2.txt. Can someone please provide some enlightenment? Is it maybe because the gravity data is not put into an array- it's just values that get looped through?
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
public class GravityV1
{
//print the data to screen
public static void printResults(String[] names, double[] diameter, double[] mass, int x)
{
System.out.printf("%-10s%21.2f%20.4e",names[x],diameter[x],mass[x]);
}
//calculate the surface gravity
public static double calcGravity(double m, double d)throws IOException
{
double gravity = 0.0;
gravity = (((6.67E-11) * (m)) / (Math.pow((d) / 2, 2)));
printToFile(gravity);
return gravity;
}
//writes gravity data to a text file
public static void printToFile(double gravity)throws IOException
{
File gravities = new File("gravity2.txt");
PrintWriter outFile = new PrintWriter(gravities);
outFile.printf("%2.2f\n", gravity);
}
//main method
public static void main (String [ ] args) throws IOException
{
double[] mass = { 3.30E23, 4.869E24, 5.972E24, 6.4219E23, 1.900E27, 5.68E26, 8.683E25, 1.0247E26, 1.27E22 };
double[] diameter = { 4880000, 12103000.6, 12756000.3, 6794000, 142984000, 120536000, 51118000, 49532000, 2274000 };
String[] names = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto" };
System.out.printf("%-7s%20s%20s%20s\n","Planet Name","Diameter","Mass(kg)", "g (m/s^2)");
System.out.println("=============================================================================");
for (int x = 0; x < 9; x++) {
printResults(names, diameter, mass, x);
double surfaceGravity = calcGravity(mass[x], diameter[x]);
System.out.printf("%17.2f\n", surfaceGravity);
}
System.out.println();
}
}
The output to the screen is correct, but unfortunately the file contains nothing. The file does get created, so I suppose that's one good thing... Any help is very greatly appreciated!!