我必须编写一个程序来确定太阳系中每个行星的表面引力,并打印出一张图表并将其写入文本文件。
我必须在我的程序中使用不同的静态方法,我必须将每个行星的重力,质量和半径写入数组。
我的问题是,我很确定我的代码是正确的但是我在calcGravity
得到了一个ArrayOutOfBoundsException,但我不认为我的数组是不合格的。我做了9个行星,我的数组设置为9.
我尝试了double[] gravity = {9};
和double[] gravity = {}
,但仍然无法正常使用。我现在还不确定该做什么
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
public class Gravity
{
public static double[] calcGravity(double[] radius, double[] mass)
{
double[] gravity = {9};
for(int i = 0; i < 9; i++)
{
gravity[i] = (6.67E17 * mass[i]) / (radius[i] * radius[i]);
}
return gravity;
}
public static void printResults(String[] name, double[] radius, double[] mass, double gravity[])
{
System.out.printf("%9s %8s %6s %7s","Planet", "Diameter (km)", "Mass (kg)", "g (m/s^2)\n");
System.out.println("----------------------------------------------------");
for(int i = 0; i < 9; i++)
{
System.out.printf("%9s %8s %6s %7s", name[i], Math.pow(radius[i], 2), mass[i], gravity[i]);
}
}
//print the gravity values to text file
public static void printToFile(double[] gravity)throws IOException
{
PrintWriter outFile = new PrintWriter (new File("gravity data.txt"));
for(int a = 0; a < 9; a++)
{
outFile.println(gravity[a]);
}
}
public static void main(String[] args)throws IOException
{
// Initialize variables
String[] names = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};
double[] radii = {2439.7, 6051.9, 6378, 3402.5, 71492, 60270, 25562, 24774, 1195};
double[] mass = {3.30E23, 4.87E24, 5.97E24, 6.42E23, 1.90E27, 5.68E26, 8.68E25, 1.02E26, 1.27E22};
// Processing
double[] gravities = calcGravity(radii, mass);
// Output
printResults(names, radii, mass, gravities);
printToFile(gravities);
} //end main
}//end class
答案 0 :(得分:4)
此行创建大小为1的数组,其中包含数字9:
double[] gravity = {9};
你想要
double[] gravity = new double[9];
创建double数组,里面有9个空“box”。
PS:冥王星不再是星球了:))