0

I am getting an out of bounds error on my double array in line 27 and I am not sure how to use the for loop to sum the doubles, please help

This is the program that takes the average

package exam2question2;

import javax.swing.JOptionPane;


public class Exam2Question2 {

    
    public static void main(String[] args) {
       
        String userInput = JOptionPane.showInputDialog("Please input five "
                + "double numbers seperated by commas");
        
        
        while(userInput.length() != 23){
            JOptionPane.showInputDialog("Please input five "
                + "double numbers seperated by commas");
        }
        
        String[] userStrings = userInput.split(",");
        double[] userDoubles = new double[6];
        userDoubles[1] = Double.parseDouble(userStrings[1]);
        userDoubles[2] = Double.parseDouble(userStrings[2]);
        userDoubles[3] = Double.parseDouble(userStrings[3]);
        userDoubles[4] = Double.parseDouble(userStrings[4]);
        userDoubles[5] = Double.parseDouble(userStrings[5]);
        
        double sum = 0;
        
        for(int i = 0; i < 6; i++){
            sum = userDoubles[i]; 
        }
        double average = sum/5;
        
        
    }
    
}
  • 1
    BTW, java arrays use a zero based index, so the first number would be `userStrings[0]` – Scary Wombat Oct 20 '20 at 01:12
  • But `userDoubles` is an array of 6 doubles, so why that error in the `for` loop? – CryptoFool Oct 20 '20 at 01:15
  • You are getting all mixed up in terms of 5 vs 6 values, and 0 first 1 as the first index. Your `for` loop will add up 6 values, but then you are dividing only by `5`. BTW, for the summation to work, you want `sum += userDoubles[i]; `. – CryptoFool Oct 20 '20 at 01:17

0 Answers0