我正在创建一个程序,它接受一系列数字并将这些数字中的最小对相加。失败的代码如下:
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);
}
combine 方法尚未实现。我检查了调试器,当它要执行 mergeMinimalPair
方法时,它抛出以下异常:
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
如何避免这种异常?
最佳答案
问题出在这里:
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);
}
}
您正在迭代到 books.size() - 1
。当i
正好等于books.size() - 1
时,i + 1
等于books.size()
,当你执行 books.get(i + 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);
}
}
关于java 抛出异常 java.lang.IndexOutOfBoundsException :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10372637/