2

我正在创建一个程序,它需要一系列数字并添加这些数字的最小对。失败的代码如下:

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

如何避免此异常?

4

3 回答 3

2

在代码中

for (int i = 1; i <= books.size() - 1; i++){
    if ((books.get(i) + books.get(i + 1)

i 的最大值是,book.size() - 1但是books.get(i + 1)这个索引太大了。

最简单的改变是

for (int i = 1; i < books.size() - 1; i++){
于 2012-04-29T13:56:49.913 回答
2

问题在这里:

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);
    }
}
于 2012-04-29T13:57:11.510 回答
2

您的循环从1to 开始books.size() - 1,而不是 from 0to books.size() - 2。在 Java 中,数组和集合索引总是从 0(包含)到 size(排除)。

于 2012-04-29T13:57:16.723 回答