Java newbie Array -out of bounds exception
I was tasked to write a program that prompts for 10 numbers, averages them and counts the occurance of the numbers above the average.
I followed examples provided and wrote the following program, but when I run it I get array out of bounds. I understand what the error is, just can't seem to correct it. Can someone please assist me? Thanks package flanagan_ch5_p1; import javax.swing.JOptionPane; /** * <p>Title: Chapter 5 PE 1</p> * * <p>Description: Analyzing input with arrays</p> * * <p>Copyright: Copyright (c) 2006</p> * * <p>Company: NOVA, ELI, ITP 120, Spring 06</p> * * @author Debora A. Flanagan * @version 1.0 */ public class flanagan_ch5_p1 { /**Main method*/ public static void main(String[] args) { final int TOTAL_NUMBERS = 10; int [ ] numbers = new int[ TOTAL_NUMBERS ]; int sum = 0; //Request numbers from user and convert to interger for (int i = 0; i < TOTAL_NUMBERS; i++){ String numString = JOptionPane.showInputDialog(null, "Enter a number", "P.E. 5.1 Input", JOptionPane.QUESTION_MESSAGE); //Convert string to integer numbers [ i ] = Integer.parseInt(numString); } //Compute their average sum += numbers [TOTAL_NUMBERS]; int average = sum / 10; //Find the numbers above average and count how many int numOfAbove =0; int count = 0; for (int i =0 ; i < TOTAL_NUMBERS; i++) { if (numbers [i] > average) count++; } //Prepare the results String output = "The numbers entered were "; for (int i = 0; i < TOTAL_NUMBERS; i++) { output += numbers [i] + " "; } output += "\nThe average of the numbers is " + average; output += "\nThe occurance count of the numbers above average is " + count; //Display the result JOptionPane.showMessageDialog(null, output, "P.E. 5.1 Output", JOptionPane.INFORMATION_MESSAGE); } } |
Quote:
Edit: you really want a loop to be calculating that sum: Code:
int sum = 0; |
sum += numbers [TOTAL_NUMBERS];
That line is your problem. You are creating an array that can be index from 0-9, you are indexing the array with a 10. |
Thank you for the quick response. I do apologize about the code tags, not sure how to use them.
|
All times are GMT -5. The time now is 01:05 PM. |