2013-12-12 50 views
-1

我有一個關於如何在數組上執行計算的問題。我將計算中的數組的長度用作存儲計算的數組的長度。在我的情況下,我所有的數組計算都很好,除了一個;它會顯示這個當我執行我的計劃:在陣列上執行計算

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

變化

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]); 
} 
+1

@ user2967353:在一般來說,當在一個索引變量上寫一個'for'循環時,對d來說它更好eclare'for'語句中的變量:'for(int i = 0;我<...)',並擺脫循環外的int i'聲明(我什至不知道它在哪裏聲明)。如果你已經這麼做了,編譯器會很早就發現你的錯誤。在循環之前需要初始化索引或在循環之後使用索引的最後一個值的情況相對較少。 – ajb

+0

@ user2967353:P.S.你在'calcGravity'中做了這個。所以也許在'main'中做錯了只是一個錯字。 – ajb