Help with PrintWriter - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Help with PrintWriter

Hello, I am currently taking a Computer Science course online and I am creating a program that calculates the force of gravity for each of the planets. I have to write the gravity value of each planet to a text file. However when I try to write it to the .txt file, it only writes the gravity for Neptune and not any of the other planets. Any help would be appreciated.

Here is my code:

[code]/**
* Write a description of class GravityV1 here.
*
* @author Carlos Castillo
* @version 11/29/11
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
public class GravityV1
{


public static double printResults(String[] names, int[] diameter, double[] mass, int i, double surfacegravity) {

System.out.printf("%7s%35d%35.2E%35.2f%n", names[i], diameter[i], mass[i], surfacegravity);

return surfacegravity;
}

public static void writeResults (String[] names, int[] diameter, double[] mass, int i, double planetgravity) throws IOException
{

PrintWriter outFile = new PrintWriter(new File("gravity1.txt"));

outFile.println("
" + planetgravity);
outFile.close();

}


public static void main(String[] args) throws IOException
{
System.out.printf("%7s%35s%35s%35s", "Planet", "Diameter(km)", "Mass(kg)", "Gravity(m/s^2)");
System.out.println("
=======================================================================================================================");
String planetname[] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};
double planetmasskg[] = {3.3E23, 4.87E24, 5.976E24, 6.42E23, 1.90E27, 5.69E26, 8.7E25, 1.03E26};
int planetdiameterkm[] = {4878, 12104, 12756, 6787, 142800, 120000, 51118, 49528};
double planetgravity;
double planetgravity2;
for(int i=0; i<planetdiameterkm.length; i++){


planetgravity = (((6.67E-11) * (planetmasskg[i]))/ (Math.pow((planetdiameterkm[i]/2),2)));
planetgravity2 = planetgravity / 1000000;


printResults(planetname, planetdiameterkm, planetmasskg, i, planetgravity2);
writeResults(planetname, planetdiameterkm, planetmasskg, i, planetgravity2);


}

}
}[/code]

Comments

  • OceanJeff40OceanJeff40 Posts: 9Member

    hey, thanks for help with gravity! :) If you haven't figured it out yet...which you have...just don't open the file each time through the loop, open file before loop, write to file inside loop, then close file after loop runs. - cheers

Sign In or Register to comment.