Java error assistance

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.

1 answer

  • answered 2018-08-09 00:31 snr

    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.