java引发异常java.lang.IndexOutOfBoundsException:
我正在创建一个程序,它接受一系列数字,并将这些数字的最小对相加。失败的代码如下所示:java引发异常java.lang.IndexOutOfBoundsException:,java,list,exception,indexoutofboundsexception,Java,List,Exception,Indexoutofboundsexception,我正在创建一个程序,它接受一系列数字,并将这些数字的最小对相加。失败的代码如下所示: import java.util.*; public class Library { public static void main(String[] args) { Scanner input = new Scanner(System.in); String answer; int count; int books;
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);
}
如何避免此异常?在代码中
for (int i = 1; i <= books.size() - 1; i++){
if ((books.get(i) + 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);
}
}
循环从
1
到books.size()-1
,而不是从0
到books.size()-2
。在Java中,数组和集合索引总是从0(包含)到大小(排除)
for (int i = 1; i < books.size() - 1; i++){
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);
}
}
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);
}
}