**Have it working now. I forgot to populate the Array List. How embarrassing.
I'm getting this error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:604)
at java.util.ArrayList.set(ArrayList.java:397)
at Netbooks.Calculations.topTen(Calculations.java:93)
at Netbooks.Test.main(Test.java:33)
Java Result: 1
The error refers to this specific line: aveList.set(maxBook, 0.0);
Which looks correct to me, but then again I'm new and am probably wrong...
I'm going to add some more code so you guys can check the size of the array and whatnot, hopefully catch something I didn't.
Here is the method that has the error:
public List<String> topTen() throws IOException {
Books books = new Books();
List<String> bookList = books.readBooks();
List<String> topList = new ArrayList<String>(10);
List<Double> aveList = new ArrayList<Double>();
for (int i = 0; i < 10; i++) {
double maxRating = 0.0;
int maxBook = 0;
for (int j = 0; j < aveList.size(); j++) {
if (maxRating < aveList.get(j)) {
maxRating = aveList.get(j);
maxBook = j;
}
}
topList.add(bookList.get(maxBook));
aveList.set(maxBook, 0.0);
}
return topList;
}
Here is where the ArrayList "aveList" is originally generated:
public List<Double> aveRatings() throws IOException {
Books books = new Books();
Ratings ratings = new Ratings();
PureRatings pureRatings = new PureRatings();
int numBooks = books.readBooks().size();
int numCust = ratings.readCustomers().size();
List<List<Integer>> pureRatingsList = pureRatings.parseRatingsFile();
List<Double> aveRatings = new ArrayList<Double>();
for (int j = 0; j < numBooks; j++) {
double sum = 0;
double counter = 0;
for (int i = 0; i < numCust; i++) {
if (pureRatingsList.get(i).get(j) != 0) {
sum = sum + pureRatingsList.get(i).get(j);
} else {
counter++;//Increase counter.
}
}
if (counter == numCust) {
aveRatings.add(0.0);
} else {
aveRatings.add((sum) / (numCust - counter));
}
}
return aveRatings;
}
I've been at it for a while now and can't seem to find out what's wrong. Any help would be appreciated.
2 Answers 2
It doesn't help that you're giving methods the same name as variables, but basically your topTen method isn't calling aveRatings() - it's just creating an empty list:
List<Double> aveList = new ArrayList<Double>();
It's then trying to set values in that list:
aveList.set(maxBook, 0.0);
maxBook will be 0 even if aveList is completely empty.
Did you mean to write:
List<Double> aveList = aveRatings();
? Note that I haven't looked at the details of the rest of the code - I've only looked for why you're getting your immediate exception.
5 Comments
List<> aveRatings and a method aveRatings().getAverageRatings method which would probably use an averages variable internally.From the JavaDoc for List.set()
Replaces the element at the specified position in this list with the specified element (optional operation).
You don't have anything in the List, so there's no valid index to replace.