在阵列上执行计算

时间:2013-12-12 19:06:15

标签: java arrays

我有一个关于如何在数组上执行计算的问题。我使用计算中的数组长度作为存储计算的数组的长度。就我而言,我对数组的所有计算都可以正常工作,除了一个;它在我执行程序时显示:

run:
Planets:              Mercury               Venus               Earth                Mars             Jupiter              Saturn              Uranus             Neptune               Pluto
Radius:               2439.70             6051.90             6378.00             3402.50            71492.00            60270.00            25562.00            24774.00             1195.00
Mass:                3.30e+23            4.87e+24            5.97e+24            6.42e+23            1.90e+27            5.68e+26            8.68e+25            1.02e+26            1.31e+22
Gravity:                 3.70                8.87                9.79                   3.70               24.78               10.44                8.86               11.13                0.61


3.7
8.87
9.79
3.7
24.78
10.44
8.86
11.13
0.61
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at GravityV1.main(GravityV1.java:118)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

以下是我的代码片段:

public class GravityV1
{
// calcGravity returns an array of doubles containing teh gravity values
//and takes two arrays of doubles as parameters for the radius values and mass
public static double[] calcGravity(double[] radius, double[] mass)
{
    // fill in code here
        double[] grav = new double[radius.length];
        for(int i = 0; i < radius.length; i++){
            grav[i] = (6.67E-17) * mass[i] / Math.pow(radius[i], 2);
        }
        return grav;
    // The formula to calculate gravity is:
    // 6.67E-17 times the massOfPlanet divided by the radius of the planet squared
}
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[] masses = {3.3022 * Math.pow(10,23), 4.8685 * Math.pow(10,24), 5.9736 * Math.pow(10,24), 6.4185 * Math.pow(10,23),
                1.8986 * Math.pow(10,27), 5.6846 * Math.pow(10,26), 8.6810 * Math.pow(10,25), 1.0243 * Math.pow(10,26), 1.312 *
                    Math.pow(10,22)};
// // calculate my weight on each planet

            // declare & initialize my weight variable
            double myWeight = 123.0;

            // array for storage
            double[] weight = new double[gravities.length];

            // for loop
            for(i = 0; i < gravities.length; i++){
                weight[i] = myWeight * gravities[i];
            }
            System.out.println(weight[i]);

1 个答案:

答案 0 :(得分:1)

更改

 for(i = 0; i < gravities.length; i++){
       weight[i] = myWeight * gravities[i];
 }
 System.out.println(weight[i]);

 for(i = 0; i < gravities.length; i++){
       weight[i] = myWeight * gravities[i];
       System.out.println(weight[i]);
 }
相关问题