import java.util.Scanner;
import java.lang.Math.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class PlanetGravity {
public static double[] Gravity(double[] mass, double[] diameters){
// for statement
double [] gravity = new double[mass.length];
double G = 6.67e-11;
for (int i = 0; i < mass.length; i++){
gravity[i] = ((G * mass[i]) / Math.sqrt((diameters[i]/2)));
}
return gravity;
}
public static void outPrint(String[] planets, double[] diameters, double[] mass, double[] gravity) {
System.out.println("Planetary Data");
System.out.println("Planet Diameter (km) Mass (kg) Gravity (m/s^2)");
System.out.println("");
for (int i = 0; i < planets.length; i++) {
System.out.printf(planets[i], diameters[i], mass[i], gravity[i]);
}
}
public static void fileWriter(double[] info) throws IOException {
File myFile = new File ("gravity.txt");
PrintWriter outFile = new PrintWriter(myFile);
for (int i = 0; i < info.length; i++) {
outFile.println(info[i]);
}
outFile.close();
}
// instance variables - replace the example below with your own
public static void main(String[] args)throws IOException {
// initialise instance variables
String [] planets = {"Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune"};
double [] diameters = {4880.0, 12103.6, 12756.3, 6794.0, 142984.0, 120536.0, 51118.0, 49532.0};
double [] mass = {3.30e23, 4.869e24, 5.972e24, 6.4219e23, 1.900e27, 5.68e26, 8.683e25, 1.0247e26};
double [] planetGravity = Gravity(mass, diameters);
outPrint(planets, diameters, mass, planetGravity);
fileWriter(planetGravity);
}
}
我认为这是最后一个无法正常工作的静态方法部分,我不确定为什么会这样,或者也可能是我后来忽略了格式化。.但是我之前已经做过,并且在以前的程序,不确定为什么现在不起作用
答案 0 :(得分:1)
System.out.printf(planets[i], diameters[i], mass[i], gravity[i]);
PrintStream.printf
的第一个参数应为格式字符串。该行仅因为planets[i]
是String
而编译。
答案 1 :(得分:0)
String [] planets = {"Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune"};
似乎缺少一些引号,因此Planets只是一个字符串...
String [] planets = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};
printf
,如其他答案所述:
System.out.printf("%s, %f, %f, %f\n", planets[i], diameters[i], mass[i], gravity[i]);