【问题标题】:java throwing exception java.lang.IndexOutOfBoundsException:java抛出异常java.lang.IndexOutOfBoundsException:
【发布时间】:2012-05-09 12:00:57
【问题描述】:

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

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

如何避免这个异常?

【问题讨论】:

    标签: java list exception indexoutofboundsexception


    【解决方案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);
        }
    }
    

    【讨论】:

      【解决方案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++){
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-07-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-10
          • 2012-10-23
          • 2013-05-24
          • 2018-09-18
          相关资源
          最近更新 更多