2015-02-11 154 views
1

我在Greenfoot中的一所學校項目的編程和我不斷收到此錯誤:的Java:索引越界

java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 
at java.util.ArrayList.rangeCheck(ArrayList.java:635) 
at java.util.ArrayList.get(ArrayList.java:411) 
at Speler.act(Speler.java:60) 
at greenfoot.core.Simulation.actActor(Simulation.java:583) 
at greenfoot.core.Simulation.runOneLoop(Simulation.java:541) 
at greenfoot.core.Simulation.runContent(Simulation.java:215) 
at greenfoot.core.Simulation.run(Simulation.java:205) 

這段代碼:

if (Greenfoot.isKeyDown("s")) 
    { 
     int wapenID; 
     if(schietTimer < 1) 
     { 
      if(richting != null) 
      { 
       if(gebruiktWapen != -1) 
       { 
        { 
         getWorld().addObject(new Kogel(richting), getX(), getY()); 
         schietTimer = 30; 
         wapenLijst.get(gebruiktWapen).schietKogel(); 

         System.out.println(wapenLijst.size()); 

         if(wapenLijst.get(gebruiktWapen).hoeveelKogels() == 0) 
         { 
          gebruiktWapen++; 
         } 
        } 
       } 
       else 
       { 
        if(wapenLijst.size() > 0) 
        { 
         gebruiktWapen ++; 
        } 
       } 
      } 
     } 
    }  

我好像不能夠找到迄今爲止的錯誤,因爲我做了一些檢查來檢查索引。任何人都可以幫我解決這個問題嗎?

+0

如果你的錯誤發生在你提供的代碼中,你就知道它必須在這一行:'wapenLijst.get(gebruiktWapen).schietKogel();'用調試器遍歷代碼來查看wapenLijst的大小與您用來索引ArrayList的gebruiktWapen的值進行比較。 – mstbaum 2015-02-11 15:44:22

回答

1

我會解釋的錯誤(因爲附帶的代碼實際上是導致異常的代碼)的原因,即使問題沒有代碼準確查明究竟如何發生。

java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

意味着你正在訪問大小1的List與索引1指標的Java是從零開始,因此索引:1指列表中的第二元件。沒有第二個因素,因此是例外。

從你給你只有一個列表的代碼,所以錯誤發生在這裏:

wapenLijst.get(gebruiktWapen).schietKogel(); 

在你的應用程序給定的狀態,wapenLijst有一個元素和gebruiktWapen爲1。按照說明上面,你嘗試訪問列表中的第二個元素時,只有一個。

你能否以某種方式實施一些不允許gebruiktWapen變得大於wapenLijst.size()的檢查?