Reputation: 73
I am creating a program that takes a series of numbers and adds the minimal pair of these numbers. The failing code follows:
import java.util.*;
public class Library {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String answer;
int count;
int books;
int writers;
List<Integer> booksList = new LinkedList<>();
System.out.printf("Numbers: ");
answer = input.nextLine();
String[] arr = answer.split(" ");
for (String num : arr) {
booksList.add(Integer.parseInt(num));
}
books = booksList.remove(0);
writers = booksList.remove(0);
while (booksList.size() > writers) {
mergeMinimalPair(booksList);
}
}
public static void mergeMinimalPair(List<Integer> books) {
int index = 0;
int minValue = books.get(0) + books.get(1);
for (int i = 1; i <= books.size() - 1; i++){
if ((books.get(i) + books.get(i + 1)) < minValue){
index = i;
minValue = books.get(i) + books.get(i + 1);
}
}
//combine(books, index, index + 1);
}
The combine method is not yet implemented. I checked with the debugger and when it is about to execute the mergeMinimalPair
method, it throws the following exception:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 7, Size: 7
at java.util.LinkedList.checkElementIndex(LinkedList.java:553)
at java.util.LinkedList.get(LinkedList.java:474)
at Library.mergeMinimalPair(Library.java:40)
at Library.main(Library.java:29)
Java Result: 1
How do I avoid this exception?
Upvotes: 2
Views: 6503
Reputation: 691795
Your loop goes from 1
to books.size() - 1
, instead of going from 0
to books.size() - 2
. Arrays and collections indices always go from 0 (included) to size (excluded) in Java.
Upvotes: 2
Reputation: 62439
The problem is here:
for (int i = 1; i <= books.size() - 1; i++){
if ((books.get(i) + books.get(i + 1)) < minValue){
index = i;
minValue = books.get(i) + books.get(i + 1);
}
}
You are iterating up to books.size() - 1
. When i
is exactly equal to books.size() - 1
, i + 1
is equal to books.size()
, which is considered out of bounds when you do books.get(i + 1)
. Fix:
for (int i = 1; i < books.size() - 1; i++){
if ((books.get(i) + books.get(i + 1)) < minValue){
index = i;
minValue = books.get(i) + books.get(i + 1);
}
}
Upvotes: 2
Reputation: 533550
In the code
for (int i = 1; i <= books.size() - 1; i++){
if ((books.get(i) + books.get(i + 1)
The largest value for i is book.size() - 1
but for books.get(i + 1)
this index is too large.
The simplest change is
for (int i = 1; i < books.size() - 1; i++){
Upvotes: 2