public class WeightOnPlanetsV1
{
public static double[] calcWeight(double[] gravity, double[]mass)
{
double[] weight = new double[gravity.length];
for (int i = 0; i < gravity.length; i++) {
weight[i] = (mass[i] * 1000)/gravity[i];
weight[i] = weight[i]/433.59237;
}
return weight;
}
public static double[] takeFromFile(double[] gravity)throws IOException
{
File fileName = new File("GravityResults.txt");
Scanner inFile = new Scanner(fileName);
for (int i = 0; i < gravity.length; i++) {
gravity[i] = inFile.nextDouble();
gravity[i] = gravity[i]/10;
}
inFile.close();
return gravity;
}
public static void printResults(String[] names, double[] gravity, double weight[])
{
System.out.printf("%37s \n","My Weight on the Planets");
System.out.printf("%5s %20s %15s \n","Planet","Gravity","Weight(lbs)");
System.out.println("---------------------------------------");
for (int i = 0; i < names.length; i++) {
System.out.printf("%5s %10f %15f \n",names[i], gravity[i], weight[i]);
}
}
public static void main(String[] args)throws IOException
{
String[] names = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto"};
double[] weightOnPlanets = {100, 100, 100, 100, 100, 100, 100, 100, 100};
double[] gravity = {};
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)};
double[] gravities = takeFromFile(gravity);
double[] finalWeights = calcWeight(gravities,masses);
printResults(names, gravities, finalWeights);
}
}
我的錯誤獲取ArrayOutofBoundsException來自在我的for循環
for (int i = 0; i < names.length; i++) {
System.out.printf("%5s %10f %15f \n",names[i], gravity[i], weight[i]);
}
當我嘗試打印結果。它給了我
java.lang.ArrayIndexOutOfBoundsException: 1
at WeightOnPlanetsV1.printResults(WeightOnPlanetsV1.java:45)
at WeightOnPlanetsV1.main(WeightOnPlanetsV1.java:63)
的錯誤
當你得到這個異常時,你是否嘗試在Eclipse的控制檯上打印異常? –