In my online computer science class I have to write a program to determine the surface gravity on each planet in the solar system. I have gotten almost every aspect of it to
Two problems:
1) You are overwriting the file each time. printResultsToFile
should take the whole array, not just one datum. Call it from outside your loop.
2) Consider entering your floating point numbers as 2.08e24 for brevity.
private void printResultsToFile(double result[]) {
PrintWriter pw = new PrintWriter(new FileWriter("planetaryData.txt"));
for (int i=0; i< result.length; i++) {
pw.printf("%.2f%n", result[i]);
}
pw.close();
}
the following code also works to open file name planetaryData.txt.
PrintWriter outFile = new PrintWriter("planetaryData.txt");
Do this in order to create a PrinterWriter
working with a FileWriter
in append mode:
PrintWriter outFile = new PrintWriter(new FileWriter("planetaryData.txt", true));
From Mkyong's tutorials:
FileWriter, a character stream to write characters to file. By default, it will replace all the existing content with new content, however, when you specified a true (boolean) value as the second argument in FileWriter constructor, it will keep the existing content and append the new content in the end of the file.
You can use something like -
PrintWriter outputFile = new PrintWriter(new FileWriter(file, true));