0

我必须编写一个程序来确定我们太阳系中每个行星的表面重力,并让它打印出图表并将其写入文本文件。

我必须在我的程序中使用不同的静态方法,并且我必须将每个行星的重力、质量和半径写入一个数组。

我的问题是,我很确定我的代码是正确的,但我不断收到 ArrayOutOfBoundsException calcGravity,但我认为我的数组没有超出范围。我正在做 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
4

1 回答 1

4

此行创建大小为 1 的数组,其中包含数字 9:

double[] gravity = {9};

你要

double[] gravity = new double[9];

它创建了内部有 9 个空“框”的 double 数组。

PS:冥王星不再是行星了:)

于 2013-10-12T16:28:53.393 回答