2012-04-29 168 views
2

我正在創建一個程序,它需要一系列數字並添加這些數字的最小對數。失敗代碼如下:java拋出異常java.lang.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; 
     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); 
    } 

聯合方法尚未實施。我與調試檢查,當它即將執行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 

如何避免此異常?

回答

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); 
    } 
} 
2

在代碼

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

最大的i值是book.size() - 1books.get(i + 1)這個指數是太大。

最簡單的變化是

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

你的循環從1去而不是去從0books.size() - 2books.size() - 1。 Java中的數組和索引總是從0(包含)到size(不包括)。