-3

Having an issue pin pointing my last issue with this program. It is designed to take 3 test scores input by the user. Then divide by the number of test scores for the average. I run the program and am able to get the input boxes to display although when i reach the final step I receive the error... "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Java_Lab_5.main(Java_Lab_5.java:40)

Here is my code

import java.util.SortedSet;
import java.util.TreeSet;
import javax.swing.JOptionPane;
import javax.swing.JFrame;

    public class Java_Lab_5 {

        public static void main(String[] args) {


 {

       {

            String test1= JOptionPane.showInputDialog("Test Score 1: ");

            String test2= JOptionPane.showInputDialog("Test Score 2: ");

            String test3= JOptionPane.showInputDialog("Test Score 3: ");

            int int1 = Integer.parseInt(test1);
            int int2 = Integer.parseInt(test2);
            int int3 = Integer.parseInt(test3);

            SortedSet<Integer> set = new TreeSet<>();
            set.add(int1);
            set.add(int2);
            set.add(int3);

            Integer [] intArray = set.toArray(new Integer[3]);
            JFrame frame = new JFrame();
            JOptionPane.showInternalMessageDialog(frame.getContentPane(), 
String.format("Result %f", (intArray[1] + intArray[2] + intArray[3]) / 3.0));

        }

    }

}

I have googled and searched around a bit anyone who can possibly point me in the right direction would be a great help. Thanks in advance.

Ryan Luber
  • 41
  • 5

1 Answers1

2

You set the array size 3. Index of an array starts from 0. It should be,

((intArray[0] + intArray[1] + intArray[2]) / 3.0)

Moreover, what if the all test scores are same? I mean you are using Set in which an element only occurs once.

  • Good point about the `Set` – Scary Wombat Aug 09 '18 at 00:35
  • I see what you're saying, and replaced that line of code and re ran the program. I input test1 as 70, test2 as 80, and test3 as 90. Although the average i am getting is 56.666667. Shouldn't the average be 80? – Ryan Luber Aug 09 '18 at 00:37
  • i see what i was doing wrong now, Thank you for your help. I am new to this website and am still fully learning the ins and outs of if. I will check off when something is helpful. – Ryan Luber Aug 09 '18 at 00:42