-1

This program uses the ArrayList class, and I get an Exception while running, what is the problem? I couldn't find any logical problem!

public static ArrayList<Double> differenceArray(ArrayList<Double> a, double avg) {

    ArrayList<Double> temp = new ArrayList<>(a.size());
    for (int i = 0; i < a.size(); i++) {
        temp.set(i, avg - a.get(i));

    }
    return temp;
}

public static void showScoresDiff(ArrayList<Double> a) {

    fillArray(a);
    double avg = computeAvg(a);
    double diff;
    for (int i = 0; i < a.size(); i++) {

        diff = avg - a.get(i);

        System.out.println("the diffrence between the avarege " + avg + " and the element " + a.get(i) + " is " + Math.abs(diff));
    }

    System.out.println("\n");

    ArrayList<Double> newArray = differenceArray(a, avg);
    for (int i = 0; i < a.size(); i++) {
        System.out.println("The " + (i + 1) + "th " + "element of the difference array is: " + newArray.get(i));
    }
}

{ and here is the output: enter image description here]1

Blockquote

  • Add something to an empty list with [`add`](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#add-E-), not [`set`](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#set-int-E-). – khelwood Feb 14 '21 at 16:48

1 Answers1

2

The problem is there in the following lines:

 ArrayList<Double> temp = new ArrayList<>(a.size());
    for (int i = 0; i < a.size(); i++) {
        temp.set(i, avg - a.get(i));

The statement, ArrayList<Double> temp = new ArrayList<>(a.size()) does not initialize temp with as many elements as a.size() i.e. the size of temp is still 0 after this statement is executed.

Given below is the description of ArrayList(int initialCapacity):

Constructs an empty list with the specified initial capacity.

Since the size of temp is 0, the statement, temp.set(i, avg - a.get(i)) will throw IndexOutOfBoundsException.

If you want temp to be initialized with the elements of a, you can do it as follows:

ArrayList<Double> temp = new ArrayList<>(a);

Now, you can set the elements up to the index, a.size() - 1.

--OR--

If you simply want to add something to temp, you can use ArrayList#add(E e) e.g. temp.add(5.5).

Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72