0

I don't know why it throws the exception any ideals??

heres my error: the line it tells me is throwing the exception is highlighted in red:

run:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at lab32analyzingscores.Main.main(Main.java:15)
Java Result: 1
BUILD SUCCESSFUL (total time: 11 seconds)

package lab32analyzingscores;
import javax.swing.JOptionPane;
/**
 *
 * @author Joe
 */
public class Main {
    public static void main(String[] args) {
        double[] score = new double[4];
        double sum = 0;
        int count = 0;

    do {
      String scoreString = JOptionPane.showInputDialog(null, "Enter a new score");
      score[count] = Double.parseDouble(scoreString);
      sum += score[count];
    }
    
    while (score[count++] >= 0);

    double average = (sum - score[count]) / (score[count] - 1);

    int numOfAbove = 0;
    int numOfBelow = 0;
    for (int i = 0; i < count -1; i++)
      if (score[i] >= average)
        numOfAbove++;
      else
        numOfBelow++;

    System.out.println("Average is " + average);
    System.out.println("Number of scores above or equal to the average " + numOfAbove);
    System.out.println("Number of scores below the average " + numOfBelow);
  }
}
2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by deleti0n
0
do {
      String scoreString = JOptionPane.showInputDialog(null, "Enter a new score");
      score[count] = Double.parseDouble(scoreString);
      sum += score[count];
    }
    
    [U][B]while (score[count++] >= 0);[/B][/U]

The highlighted line is where you have got it wrong. You are supposed to ensure that the array doesn't go out of bounds... i.e, count should be less than 4. Instead, you are checking for score[count++]>=0 ..... where are you checking for the array bounds ?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.