我是新手,我尝试编写一个程序来计算数组中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开头,所以这就是我选择命令数组-1的原因,你能告诉我或者说明我做错了吗?
答案 0 :(得分:2)
你有一个包含10个元素的数组,并在循环中请求下一个元素,直到用户输入负值。由于用户总是输入25,因此循环永远不会停止,直到它到达第11个元素。访问10个元素数组的第11个元素(在索引10处)会抛出您看到的异常。
答案 1 :(得分:1)
如果您想要准确读取10个数字,请更改此处的阅读输入部分
//GET INPUT TEST SCORES
for(int i=0;i<10;i++)
System.out.print("Enter Score: ");
inputDouble = input.nextDouble();
testScores[i] = inputDouble;
sum += inputDouble;
}