Issue
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: ]1
Blockquote
Solution
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)
.
Answered By - Arvind Kumar Avinash
Answer Checked By - David Goodson (JavaFixing Volunteer)