Note that there are some explanatory texts on larger screens.

plurals
  1. POJava: ArrayIndexOutOfBoundsException with "foreach" and arrays?
    primarykey
    data
    text
    <p>I'm making a game and I need help using the <code>foreach</code> and the array of the <code>platforms</code>. When I ran it, the console said "<code>ArrayOutOfBoundsException</code>"</p> <p>I looked online for what that means but I couldn't find that out. What is "<code>ArrayIndexOutOfBoundsException</code>"? The code goes like this:</p> <pre><code>//all imports public class Panel extends JPanel implements Runnable{ public guy Guy; public Tile[] platforms = new Tile[3]; ... public void defineObjects(){ //Set Rectangles Guy = new guy(Frame.width/2 - 45/2, 100, 45, 50); ... platforms[1] = new Tile(100, Frame.height-80, tileSize*8, tileSize); platforms[2] = new Tile(400, 350, tileSize*2, tileSize); platforms[3] = new Tile(500, 250, tileSize*4, tileSize); //set boolean true and repaint objectsDefined = true; repaint(); } public void run() { while(running){ Point bl = new Point(Guy.x, Guy.y + Guy.height); Point br = new Point(Guy.x + Guy.width, Guy.y + Guy.height); if(objectsDefined){ for(int i = 0; i &lt; platforms.length; i++) { if (platforms[i] == null) { continue; }else{ isAnyCollision = Guy.intersects(platforms[i]); isOnPlatform = platforms[i].y == br.y &amp;&amp; br.x &gt;=platforms[i].x &amp;&amp; bl.x &lt;= platforms[i].x + platforms[i].width; } } } </code></pre> <p>When I got first got the <code>NullPointerException</code> this is what I had did <code>public Tile[] platforms = new Tile[4];</code> but I hadn't defined the <code> platforms[4]</code> so then I changed the lengths of <code>platforms[]</code> to <code>platforms[3]</code>. But now it says <code>ArrayIndexOutOfBoundsException</code>.</p> <p>Any thoughts?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload