gpt4 book ai didi

java.lang.ArrayIndexOutOfBoundsException :10 异常

转载 作者:行者123 更新时间:2023-11-29 05:24:58 28 4
gpt4 key购买 nike

我是这里的新手,我尝试编写一个程序来计算数组中 10 个数字的偏差,这是我创建的代码:

package week10;

import java.util.Scanner;

public class deviation {
public static void main(String[]args) {

Scanner input = new Scanner(System.in);
double testScores[] = new double [10];
double sum = 0;

int count = 0;
int count2 = 0;
int count3 = 0;

double inputDouble = 0;
int arrayIndex = 0;

//GET INPUT TEST SCORES
while(inputDouble >= 0) {
System.out.print("Enter Score: ");

inputDouble = input.nextDouble();
if(inputDouble >= 0)
{
testScores[arrayIndex] = inputDouble;
sum += inputDouble;
}
arrayIndex++;
}

if(arrayIndex < testScores.length)
{
for (int x = arrayIndex-1; x <= testScores.length-1; x++)
{
testScores[x] = -1;
}
}

//GET NEW ARRAY WITH ONLY VALID SCORES
double[] validScores = GetValidScores(testScores, arrayIndex-1);

System.out.println(" The mean is: " + mean(validScores));
System.out.println(" The standard deviation is: " + deviation(validScores));
}

private static double[] GetValidScores(double[] inputArray, int validScoreCount) {
double[] newScores = new double[validScoreCount];
for(int z = 0; z < validScoreCount; z++)
{
newScores[z] = inputArray[z];
}
return newScores;
}

public static double deviation(double[] values) {
double sum = 0.00;

double theMean = mean(values);

for(int i =0; i < values.length; i++) {
double currentCalc = values[i] - theMean;
sum += Math.pow(currentCalc, 2);
}

sum = sum / (values.length -1);

sum = Math.sqrt(sum);

return sum;
}

public static double mean(double[] values)
{
double sum = 0.00;

for(int i=0; i < values.length; i++)
{
sum += values[i];
}

return sum / values.length;
}

}

输出:

Enter Score: 25
Enter Score: 25
Enter Score: 25
Enter Score: 25
Enter Score: 25
Enter Score: 25
Enter Score: 25
Enter Score: 25
Enter Score: 25
Enter Score: 25
Enter Score: 25

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at week10.deviation.main(deviation.java:26)"

我知道数组是 10,但它以 0 开头,所以这就是我选择命令 array-1 的原因,你能告诉我或说明我做错了什么吗?

最佳答案

您有一个包含 10 个元素的数组,并在循环中请求下一个元素,直到用户输入负值。由于用户总是输入 25,因此循环永远不会停止,直到到达第 11 个元素。访问包含 10 个元素的数组的第 11 个元素(在索引 10 处)会引发您所看到的异常。

关于java.lang.ArrayIndexOutOfBoundsException :10 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23034799/

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