2013-04-05 32 views
0

我知道这个问题已经被问了一百万次。而且我觉得这个解决方案对于几个小时没有注视过它的人来说是相当明显的。但是,我无法让自己超越界限的例外。以下是错误:Java数组列表outofbounds

exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 207493, Size: 207493 
    at java.util.ArrayList.rangeCheck(ArrayList.java:604) 
    at java.util.ArrayList.get(ArrayList.java:382) 
    at affysureselect.AffySureSelect.main(AffySureSelect.java:92) 
Java Result: 1 

我想也许这可能是由于到ArrayList的大小来发生的事情,但如果是这样的话我本来期望的误差加法的时候,而不是越来越成。这里是它垂死代码:

String chrompos; 
    ArrayList<String> chromnum = new ArrayList<String>(); 
    while ((input2 = sbuff.readLine()) != null) { 
     prse = input2.split("\t"); 
     chromnum.add(prse[0]); 
     ... 
     chrompos = prse[7]; 
    } 
    int cnt = 0; 
    int cnt2 = 0; 
    if (chromnum.get(cnt).equals(chrompos)) { // line causing my untimely death 
     end = Integer.parseInt(chromposend.get(cnt2)); 
     start = Integer.parseInt(chromposstart.get(cnt2)); 
     ... 

我甚至尝试添加:

if (cnt <= chromnum.size()) { //this line 
    if (chromnum.get(cnt).equals(chrompos)) { /before the dying line 

但它也死了,就弄,在追加。我错过了什么?

+0

'System.out.println'列表中,你会看到你有更少的元素比你想象的 – slezica 2013-04-05 03:48:34

+1

的问题是,你混淆了基于1的索引基于0的索引。如果你的列表有10个元素,元素存在的索引是'0-9'(当你使用'ArrayList.add(Object)'时,你的检查确保'ArrayList'中的索引存在'如果(CNT nickb 2013-04-05 03:50:57

回答

1

如果您正在增加cnt,请确保它始终少于chromnum.size()。

应该是─

if (cnt < chromnum.size()) 
+0

哦。咄。我知道这将是一个非常愚蠢的事情。非常感谢。我会11分钟接受。 – Stephopolis 2013-04-05 03:49:51

0

指数我不存在。您必须始终迭代到list.size() - 1

0

如果ArrayList的尺寸也为i,则无法访问索引i。最大可访问指数是i-1。因此,即使您的List的尺寸也为207493,即表示您试图访问207493 th索引的IndexOutOfBoundsException

请检查以将您的list的尺寸缩小为cnt

0

因为,按照它的样子,在如果循环您正在尝试

chromnum.get(cnt) and cnt is initialized to 0. 

所以最有可能的问题是,代码永远不会进入while循环,伸出放码在while循环之后的SOP并检查数组列表大小。

0

删除等号,

if (cnt < chromnum.size()) { //this line 
     if (chromnum.get(cnt).equals(chrompos)) { 

希望能帮助你:)

0

记住,列出从0开始,所以如果你有N个项目的列表的最后一个项目将是N - 1 (因为0是第1个要素,1是第二等)

所以,你应该写

if (cnt < chromnum.size()) { 

instea d的

if (cnt <= chromnum.size()) { 
0

1-based like Pascal:United States,English-speaking Canada。
0如C/Java:魁北克,(大部分?)欧洲。

这就是答案。问题是,电梯中的楼层是如何索引的。