java - 在我的 for 循环中获取 ArrayOutofBoundsException

标签 java arrays loops for-loop

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);
  }  
}

我的错误来自

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)

作为错误

最佳答案

您检查 names 数组的边界并访问 gravityweight 假设它们具有与 names< 相同或更大的长度

关于java - 在我的 for 循环中获取 ArrayOutofBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26960410/

相关文章:

在 C 中计算 0's and 1' 的二维数组的高度

java - 使用 HBaseTestingUtility 进行单元测试

java - 线程消费者内部的 NullPointerException

java - 无法使用 Sentinel 值退出循环

ios - 如何使用 swift 在数组中字符串的开头和结尾添加带双引号的字符串

结构中的 C++ 可变长度数组

java - 从 Controller ,数据没有转换为 html View 页面

java - 如何创建 LinkedList<Object[]>[]?

python - 需要编写一个函数来接收颜色列表,并输出它们的负颜色(来自字典的对)

java - 在用户输入后的任何时候停止?