I am a newbie here and I try to write a program that will be calculating the deviation of 10 numbers in the array, here is my code that I got created :
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;
}
}
Output:
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)"
I understand that array is 10, but it starts with a 0, so this is why I chose command array-1, can you please tell me or show what am I doing wrong?
arrayIndexstarts at 0 and goes up to 9, so when you exit thewhileloop, if you only enter 10 numbers, yourarrayIndexwill be 9. So you're actually passing 8 when you give itarrayIndex - 1.