gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:44:36 28 4
gpt4 key购买 nike

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com