Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Game problem: java.lang.IndexOutOfBoundsException with array list

  1. #1
    Member
    Join Date
    Jan 2013
    Posts
    37
    My Mood
    Relaxed
    Thanks
    1
    Thanked 1 Time in 1 Post

    Exclamation Game problem: java.lang.IndexOutOfBoundsException with array list

    When a bullit bullit hits a alien it creates this error :

    java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.get(Unknown Source)
    at com.spaceinvader.Main.colision(Main.java:291)
    at com.spaceinvader.Main.update(Main.java:190)
    at com.spaceinvader.Main.run(Main.java:126)
    at java.lang.Thread.run(Unknown Source)

    This only happens when not the first bullet on the screen hits but when the others hit a alien.
    I used an exeption to let it work but it isnt a sollid fix for errors should not occor regarly.
    Its about this code :

    private void colision() {
    		if (aliens.size() >= 1 && bulletsPlayer.size() >= 1) {
    			for (int i = 0; i < aliens.size(); i++) {
    				for (int i2 = 0; i2 < bulletsPlayer.size(); i2++) {
    					try {
    						if (aliens.get(i).getBounds().intersects(bulletsPlayer.get(i2).getBounds())) {
    							bulletsPlayer.remove(i2);
    							aliens.remove(i);
    							player.incScore(100 * niveau);
    							shotsHit++;
    							aliensKilled++;
    						}
    					} catch (Exception e) {
    						e.printStackTrace();
    					}
    				}
    			}
    		}
    		if (bulletsAlien.size() >= 1) {
    			for (int i = 0; i < bulletsAlien.size(); i++) {
    				if (player.getBounds().intersects(bulletsAlien.get(i).getBounds())) {
    					gameOverMenu = true;
    				}
    			}
    		}
    	}

    Furter source Code

    Main.java
    package com.spaceinvader;
     
    import com.spaceinvader.render.*;
    import com.spaceinvader.entity.*;
     
    import javax.swing.JFrame;
    import javax.swing.JPanel;
     
    import java.awt.Canvas;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.image.BufferStrategy;
    import java.util.ArrayList;
    import java.util.Random;
     
    public class Main extends Canvas implements Runnable, KeyListener {
    	private static final long serialVersionUID = 1L;
     
    	static Main main;
    	static Render render;
     
    	public static JFrame frame;
    	public static JPanel panel;
    	public static Random random;
    	Thread thread;
     
    	public final static int WIDTH = 400;
    	public final static int HEIGHT = 600;
    	boolean running = false;
    	static String Titel = "Space Invader";
     
    	private boolean[] keys = new boolean[65536];
    	public boolean left, right, use, back;
     
    	public static boolean pauzeMenu = true;
    	public static boolean gameOverMenu = false;
    	public static boolean waveMenu = false;
     
    	public static EntityPlayer player;
    	public static ArrayList<EntityBullet> bulletsPlayer;
    	public static ArrayList<EntityBullet> bulletsAlien;
    	public static ArrayList<EntityAlien> aliens;
     
    	public int bulletTimerPlayer = 0, bulletTimedPlayer = 25;
    	public int bulletTimerAlien = 0, bulletTimedAlien = 20;
    	public int TimerPauze = 0, TimedPauze = 30;
     
    	public static int niveau = 0;
    	public static int shotsFired = 0;
    	public static int shotsHit = 0;
    	public static int aliensKilled = 0;
     
    	public static void main(String[] args) {
    		frame = new JFrame();
    		main = new Main();
    		panel = new JPanel();
    		render = new Render();
    		random = new Random();
     
    		frame.add(panel);
    		frame.setResizable(false);
    		frame.setTitle(Titel);
    		panel.add(main);
    		frame.pack();
    		frame.setLocationRelativeTo(null);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setVisible(true);
    		main.start();
    	}
     
    	public Main() {
    		Dimension size = new Dimension(WIDTH, HEIGHT);
    		setPreferredSize(size);
    		setMinimumSize(size);
    		setMaximumSize(size);
    		addKeyListener(this);
     
    		player = new EntityPlayer();
    		player.setAlive(true);
    		player.setWidth(40);
    		player.setHeight(20);
    		player.setX(WIDTH / 2 - player.getWidth() / 2);
    		player.setY(HEIGHT - 50);
    		player.setVelX(5);
     
    		bulletsPlayer = new ArrayList<EntityBullet>();
    		bulletsAlien = new ArrayList<EntityBullet>();
    		aliens = new ArrayList<EntityAlien>();
    	}
     
    	public synchronized void start() {
    		if (running)
    			return;
    		thread = new Thread(this);
    		thread.start();
    		running = true;
    	}
     
    	public synchronized void stop() {
    		if (!running)
    			return;
    		running = false;
    		try {
    			thread.join();
    		} catch (InterruptedException e) {
    			e.printStackTrace();
    		}
    	}
     
    	public void run() {
    		int frames;
    		long lastTime = System.nanoTime();
    		long lastTimer = System.currentTimeMillis();
    		double ns = 1000000000.0 / 60.0;
    		double delta = 0;
    		frames = 0;
    		int updates = 0;
    		requestFocus();
    		while (running) {
    			long now = System.nanoTime();
    			delta += (now - lastTime) / ns;
    			lastTime = now;
    			if (delta >= 1) {
    				update();
    				updates++;
    				delta--;
    				bulletTimerPlayer++;
    				bulletTimerAlien++;
    				TimerPauze++;
    			}
    			render();
    			frames++;
    			while (System.currentTimeMillis() - lastTimer > 1000) {
    				lastTimer += 1000;
    				frame.setTitle("Space Invader " + updates + " ups, " + frames + " fps");
    				frames = 0;
    				updates = 0;
    			}
    		}
    	}
     
    	private void render() {
    		BufferStrategy bs = getBufferStrategy();
    		if (bs == null) {
    			createBufferStrategy(3);
    			return;
    		}
    		Graphics g = bs.getDrawGraphics();
    		render.render(g);
    		g.dispose();
    		bs.show();
    	}
     
    	public void updateKey() {
    		left = keys[KeyEvent.VK_LEFT];
    		right = keys[KeyEvent.VK_RIGHT];
    		use = keys[KeyEvent.VK_SPACE] || keys[KeyEvent.VK_ENTER];
    		back = keys[KeyEvent.VK_ESCAPE];
    	}
     
    	public void keyPressed(KeyEvent e) {
    		keys[e.getKeyCode()] = true;
    	}
     
    	public void keyReleased(KeyEvent e) {
    		keys[e.getKeyCode()] = false;
    	}
     
    	public void keyTyped(KeyEvent e) {
    	}
     
    	public void releaseAll() {
    		left = right = use = back = false;
    	}
     
    	private void update() {
    		if (gameOverMenu) {
    			ResetAll();
    		}
    		updateKey();
    		setPauze();
    		if (!pauzeMenu && !gameOverMenu) {
    			MovementPlayer();
    			ShootingPlayer();
    			SpawnAliens();
    			MovementAliens();
    			ShootingAliens();
    			colision();
    		}
    	}
     
    	private void ResetAll() {
    		if (TimerPauze >= TimedPauze && back) {
    			aliens.clear();
    			bulletsAlien.clear();
    			bulletsPlayer.clear();
    			player.setX(WIDTH / 2 - player.getWidth() / 2);
    			player.setY(HEIGHT - 50);
    			player.setScore(0);
    			niveau = 0;
    			niveau = 0;
    			shotsFired = 0;
    			shotsHit = 0;
    			aliensKilled = 0;
    			pauzeMenu = true;
    			gameOverMenu = false;
    			TimerPauze = 0;
    		}
    	}
     
    	private void ResetField(){
    		aliens.clear();
    		bulletsAlien.clear();
    		bulletsPlayer.clear();
    	}
     
    	private void setPauze() {
    		if (TimerPauze >= TimedPauze && pauzeMenu && back && !gameOverMenu) {
    			pauzeMenu = false;
    			TimerPauze = 0;
    		} else if (TimerPauze >= TimedPauze && !pauzeMenu && back && !gameOverMenu) {
    			pauzeMenu = true;
    			TimerPauze = 0;
    		}
     
    	}
     
    	private void ShootingAliens() {
    		if (bulletTimerAlien >= bulletTimedAlien) {
    			for (int i = 0; i < aliens.size(); i++) {
    				if (random.nextInt(1000 - 20 * niveau) == 0) {
    					bulletsAlien.add(new EntityBullet());
    					bulletsAlien.get(bulletsAlien.size() - 1).setHeight(10);
    					bulletsAlien.get(bulletsAlien.size() - 1).setWidth(10);
    					bulletsAlien.get(bulletsAlien.size() - 1).setX(aliens.get(i).getX() + aliens.get(i).getHeight() / 2 + bulletsAlien.get(bulletsAlien.size() - 1).getWidth() / 2);
    					bulletsAlien.get(bulletsAlien.size() - 1).setY(aliens.get(i).getY() + bulletsAlien.get(bulletsAlien.size() - 1).getHeight());
    					bulletsAlien.get(bulletsAlien.size() - 1).setVelY(1.8 + 0.2 * niveau);
    					bulletTimerAlien = 0;
    				}
    			}
    		}
    		if (bulletsAlien.size() >= 1) {
    			for (int i = 0; i < bulletsAlien.size(); i++) {
    				bulletsAlien.get(i).incY(bulletsAlien.get(i).getVelY());
    				if (bulletsAlien.get(i).getY() > HEIGHT) {
    					bulletsAlien.remove(i);
    				}
    			}
    		}
    	}
     
    	private void MovementAliens() {
    		if (aliens.size() >= 1) {
    			for (int i = 0; i < aliens.size(); i++) {
    				if (aliens.get(i).getDown() == false && aliens.get(i).getUp() == false && aliens.get(i).getRight() == false && aliens.get(i).getLeft() == false) {
    					aliens.get(i).setRight(true);
    				}
    				if (aliens.get(i).getUp()) {
    					aliens.get(i).incY(-aliens.get(i).getVelY());
    				}
    				if (aliens.get(i).getDown()) {
    					aliens.get(i).incY(aliens.get(i).getVelY());
    				}
    				if (aliens.get(i).getRight()) {
    					aliens.get(i).incX(aliens.get(i).getVelX());
    				}
    				if (aliens.get(i).getLeft()) {
    					aliens.get(i).incX(-aliens.get(i).getVelX());
    				}
    				if (aliens.get(i).getX() <= 0) {
    					aliens.get(i).setRight(true);
    					aliens.get(i).setLeft(false);
    					aliens.get(i).incY(aliens.get(i).getHeight() * 1.5);
    				}
    				if (aliens.get(i).getX() >= WIDTH - aliens.get(i).getWidth()) {
    					aliens.get(i).setRight(false);
    					aliens.get(i).setLeft(true);
    					aliens.get(i).incY(aliens.get(i).getHeight() * 1.5);
    				}
    			}
    		}
    	}
     
    	private void colision() {
    		if (aliens.size() >= 1 && bulletsPlayer.size() >= 1) {
    			for (int i = 0; i < aliens.size(); i++) {
    				for (int i2 = 0; i2 < bulletsPlayer.size(); i2++) {
    					try {
    						if (aliens.get(i).getBounds().intersects(bulletsPlayer.get(i2).getBounds())) {
    							bulletsPlayer.remove(i2);
    							aliens.remove(i);
    							player.incScore(100 * niveau);
    							shotsHit++;
    							aliensKilled++;
    						}
    					} catch (Exception e) {
    						e.printStackTrace();
    					}
    				}
    			}
    		}
    		if (bulletsAlien.size() >= 1) {
    			for (int i = 0; i < bulletsAlien.size(); i++) {
    				if (player.getBounds().intersects(bulletsAlien.get(i).getBounds())) {
    					gameOverMenu = true;
    				}
    			}
    		}
    	}
     
    	private void SpawnAliens() {
    		int ALIENSWIDTH = 7;
    		int ALIENSHEIGHT = 4;
    		if (aliens.size() == 0 && !waveMenu) {
    			waveMenu = true;
    			niveau++;
    		}
    		if (waveMenu && use) {
    			ResetField();
    			waveMenu = false;
    			bulletTimerPlayer = 0;
    			for (int i = 0; i < ALIENSWIDTH; i++) {
    				for (int i2 = 0; i2 < ALIENSHEIGHT; i2++) {
    					aliens.add(new EntityAlien());
    					aliens.get(aliens.size() - 1).setHeight(15);
    					aliens.get(aliens.size() - 1).setWidth(15);
    					aliens.get(aliens.size() - 1).setX(i * 50 + 50);
    					aliens.get(aliens.size() - 1).setY(i2 * 45);
    					aliens.get(aliens.size() - 1).setVelX(0.5 + 0.2 * niveau);
    					aliens.get(aliens.size() - 1).setVelY(0.5 + 0.2 * niveau);
    					aliens.get(aliens.size() - 1).setDown(false);
    					aliens.get(aliens.size() - 1).setUp(false);
    					aliens.get(aliens.size() - 1).setLeft(false);
    					aliens.get(aliens.size() - 1).setRight(false);
    				}
    			}
    		}
    	}
     
    	private void ShootingPlayer() {
    		if (bulletTimerPlayer >= bulletTimedPlayer) {
    			if (use && !waveMenu) {
    				if (!(player.getScore() == 0)) {
    					player.incScore(-10);
    				}
    				bulletTimerPlayer = 0;
    				bulletsPlayer.add(new EntityBullet());
    				bulletsPlayer.get(bulletsPlayer.size() - 1).setHeight(10);
    				bulletsPlayer.get(bulletsPlayer.size() - 1).setWidth(10);
    				bulletsPlayer.get(bulletsPlayer.size() - 1).setX(player.getX() + player.getHeight() / 2 + bulletsPlayer.get(bulletsPlayer.size() - 1).getWidth() / 2);
    				bulletsPlayer.get(bulletsPlayer.size() - 1).setY(player.getY() - bulletsPlayer.get(bulletsPlayer.size() - 1).getHeight());
    				bulletsPlayer.get(bulletsPlayer.size() - 1).setVelY(6.0);
    				shotsFired++;
    			}
    		}
    		if (bulletsPlayer.size() > 0) {
    			for (int i = 0; i < bulletsPlayer.size(); i++) {
    				bulletsPlayer.get(i).incY(-bulletsPlayer.get(i).getVelY());
    			}
    			for (int i = 0; i < bulletsPlayer.size(); i++) {
    				if (bulletsPlayer.get(i).getY() < 0) {
    					bulletsPlayer.remove(i);
    				}
    			}
    		}
    	}
     
    	private void MovementPlayer() {
    		if (left && player.getX() > 0) {
    			player.incX(-player.getVelX());
    		}
    		if (right && player.getX() + player.getWidth() < WIDTH) {
    			player.incX(player.getVelX());
    		}
    	}
    }

    SpaceInvaderApplet.java
    package com.spaceinvader;
     
    import java.applet.Applet;
    import java.awt.BorderLayout;
    import java.util.Random;
     
    import javax.swing.JPanel;
     
    import com.spaceinvader.render.Render;
     
     
    public class SpaceInvaderApplet extends Applet {
    	private static final long serialVersionUID = 1L;
     
    	private Main main = new Main();
    	private JPanel panel;
     
    	public void init() {
    		panel = new JPanel();
    		Main.render = new Render();
    		Main.random = new Random();
    		setLayout(new BorderLayout());
    		add(panel);
    		panel.add(main);
    		setSize(Main.WIDTH, Main.HEIGHT);
    	}
     
    	public void start() {
    		main.start();
    	}
     
    	public void stop() {
    		main.stop();
    	}
     
    }

    BaseEntity.java
    package com.spaceinvader.entity;
     
    public class BaseEntity {
     
    	private double x, y;
    	private double height, width;
    	private double velX, velY;
    	private boolean alive;
     
    	//accessor
    	public boolean getAlive(){return alive;}
    	public double getX(){ return x;}
    	public double getY(){ return y;}
    	public double getHeight(){return height;}
    	public double getWidth(){return width;}
    	public double getVelX(){return velX;}
    	public double getVelY(){return velY;}
     
    	//mutators
    	public void setAlive(boolean alive){this.alive = alive;}
    	public void setX(double x){this.x = x;}
    	public void setY(double y){this.y = y;}
    	public void incX(double i){this.x += i;}
    	public void incY(double d){this.y += d;}
    	public void setHeight(double height){this.height = height;}
    	public void setWidth(double width){this.width = width;}
    	public void incHeight(double i){this.height += i;}
    	public void incWidth(double i){this.width += i;}
    	public void setVelX(double velX){this.velX = velX;}
    	public void setVelY(double velY){this.velY = velY;}
     
    	BaseEntity(){
    		setAlive(false);
    		setX(0);
    		setY(0);
    		setWidth(0);
    		setHeight(0);
    	}
    }

    EntityAlien.java
    package com.spaceinvader.entity;
     
    import java.awt.Rectangle;
     
    public class EntityAlien extends BaseEntity {
     
    	boolean right,left, up, down;
     
    	public Rectangle getBounds() {
    		Rectangle r;
    		r = new Rectangle((int) getX(), (int) getY(), (int) getWidth(), (int) getHeight());
    		return r;
    	}
     
    	public EntityAlien() {
    		setAlive(true);
    	}
     
    	//accessor
    	public boolean getRight(){return right;}
    	public boolean getLeft(){return left;}
    	public boolean getUp(){return up;}
    	public boolean getDown(){return down;}
     
    	//mutator
    	public void setRight(boolean right){this.right = right;}
    	public void setLeft(boolean left){this.left = left;}
    	public void setUp(boolean up){this.up = up;}
    	public void setDown(boolean down){this.down = down;}
    }

    EntityBullet.java
    package com.spaceinvader.entity;
     
    import java.awt.Rectangle;
     
    public class EntityBullet extends BaseEntity {
     
    	public Rectangle getBounds() {
    		Rectangle r;
    		r = new Rectangle((int) getX(), (int) getY(), (int) getWidth(), (int) getHeight());
    		return r;
    	}
     
    	public EntityBullet() {
    		setAlive(false);
    	}
    }

    EntityPlayer
    package com.spaceinvader.entity;
     
    import java.awt.Rectangle;
     
    public class EntityPlayer extends BaseEntity {
     
    	public int score;
     
    	public Rectangle getBounds() {
    		Rectangle r;
    		r = new Rectangle((int) getX(), (int) getY(), (int) getWidth(), (int) getHeight());
    		return r;
    	}
     
    	public EntityPlayer() {
    		setAlive(true);
    	}
     
    	//accessor
    	public int getScore(){return score;}
     
    	//mutator
    	public void setScore(int score){this.score = score;}
    	public void incScore(int i){this.score += i;}
    }

    Render.java
    package com.spaceinvader.render;
     
    import com.spaceinvader.Main;
     
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
     
    public class Render {
     
    	Main main;
     
    	Font font = new Font("Arial", Font.BOLD, 10);
    	Font fontPauzeBig = new Font("Arial", Font.BOLD, 30);
    	Font fontPauze = new Font("Arial", Font.BOLD, 15);
     
    	public Render() {
    		main = new Main();
    	}
     
    	public void render(Graphics g) {
    		g.setColor(Color.black);
    		g.fillRect(0, 0, Main.WIDTH, Main.HEIGHT);
     
    		if (!Main.pauzeMenu || Main.gameOverMenu) {
    			if (!Main.waveMenu) {
    				g.setColor(Color.red);
    				g.fillRect((int) Main.player.getX(), (int) Main.player.getY(), (int) Main.player.getWidth(), (int) Main.player.getHeight());
     
    				if (Main.bulletsPlayer.size() > 0) {
    					for (int i = 0; i < Main.bulletsPlayer.size(); i++) {
    						g.setColor(Color.blue);
    						g.fillRect((int) Main.bulletsPlayer.get(i).getX(), (int) Main.bulletsPlayer.get(i).getY(), (int) Main.bulletsPlayer.get(i).getWidth(), (int) Main.bulletsPlayer.get(i).getHeight());
    					}
    				}
    				if (Main.bulletsAlien.size() > 0) {
    					for (int i = 0; i < Main.bulletsAlien.size(); i++) {
    						g.setColor(Color.yellow);
    						g.fillRect((int) Main.bulletsAlien.get(i).getX(), (int) Main.bulletsAlien.get(i).getY(), (int) Main.bulletsAlien.get(i).getWidth(), (int) Main.bulletsAlien.get(i).getHeight());
    					}
    				}
     
    				if (Main.aliens.size() > 0) {
    					for (int i = 0; i < Main.aliens.size(); i++) {
    						g.setColor(Color.green);
    						g.fillRect((int) Main.aliens.get(i).getX(), (int) Main.aliens.get(i).getY(), (int) Main.aliens.get(i).getWidth(), (int) Main.aliens.get(i).getHeight());
    					}
    				}
    				g.setColor(Color.green);
    				g.setFont(font);
    				g.drawString("Level: " + Main.niveau, 0, 10);
    				g.drawString("Score: " + Main.player.getScore(), 0, 20);
    				g.drawString("Shots fired: " + Main.shotsFired, 0, 30);
    				g.drawString("Shots hit: " + Main.shotsHit, 0, 40);
    				g.drawString("Aliens killed: " + Main.aliensKilled, 0, 50);
    				if (Main.gameOverMenu) {
    					g.setFont(fontPauzeBig);
    					g.drawString("GAME OVER", Main.WIDTH / 2 - 100, Main.HEIGHT / 2 - 30);
    					g.setFont(fontPauze);
    					g.drawString("Score : " + Main.player.getScore(), Main.WIDTH / 2 - 95, Main.HEIGHT / 2);
    					g.drawString("Press escape to go back", Main.WIDTH / 2 - 95, Main.HEIGHT / 2 + 30);
    				}
    			} else {
    				g.setColor(Color.green);
    				g.setFont(fontPauzeBig);
    				g.drawString("Wave " + Main.niveau, Main.WIDTH / 2 - 50, Main.HEIGHT / 2);
    				g.setFont(fontPauze);
    				g.drawString("Press spacebar to start ", Main.WIDTH / 2 - 80, Main.HEIGHT / 2 + 30);
    			}
    		}
    		if (Main.pauzeMenu && !Main.gameOverMenu) {
    			g.setColor(Color.green);
    			g.setFont(fontPauzeBig);
    			g.drawString("press escape", Main.WIDTH / 2 - 100, Main.HEIGHT / 2 - 150);
    			g.drawString("to start/continue", Main.WIDTH / 2 - 120, Main.HEIGHT / 2 + 40 - 150);
    			g.setFont(fontPauze);
    			g.drawString("Controls", Main.WIDTH / 2 - 120, Main.HEIGHT / 2 + 30);
    			g.drawString("-Right/Left arrow keys to move", Main.WIDTH / 2 - 120, Main.HEIGHT / 2 + 45);
    			g.drawString("-Spacebar to shoot", Main.WIDTH / 2 - 120, Main.HEIGHT / 2 + 60);
    			g.drawString("-Escape to pause", Main.WIDTH / 2 - 120, Main.HEIGHT / 2 + 75);
    		}
    	}
    }


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    3,415
    My Mood
    Mellow
    Thanks
    85
    Thanked 473 Times in 464 Posts

    Default Re: Game problem: java.lang.IndexOutOfBoundsException with array list

    Theory: removing a bullet and an alien in the try clause is changing the size of their respective ArrayLists so that the for loop conditions become incorrect. That allows the loop control variables, i and i2, to become larger than or outside the bounds of the modified ArrayLists.

  3. The Following User Says Thank You to GregBrannon For This Useful Post:

    The_pizzaguy (August 23rd, 2013)

  4. #3
    Member
    Join Date
    Jan 2013
    Posts
    37
    My Mood
    Relaxed
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: Game problem: java.lang.IndexOutOfBoundsException with array list

    Thanks XD
    I hadnt thought of that yet thank you

  5. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    3,415
    My Mood
    Mellow
    Thanks
    85
    Thanked 473 Times in 464 Posts

    Default Re: Game problem: java.lang.IndexOutOfBoundsException with array list

    Glad to help. Changing loop control variables or the collection being iterated inside the loop - especially the size/length/etc. - should always raise red flags. It's doable but requires increased vigilance to avoid the kind of errors you've encountered.

  6. #5
    Member
    Join Date
    Jan 2013
    Posts
    37
    My Mood
    Relaxed
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: Game problem: java.lang.IndexOutOfBoundsException with array list

    I found a fix. What i did is i made 2 more array list for the dead aliens and bullets to store the index into. Afther the loops have ended i made 2 extra loops to delete the aliens and bullets.

    Code :
    private void colision() {
    		ArrayList<Integer> deadAliens = new ArrayList<>();
    		ArrayList<Integer> deadBullets = new ArrayList<>();
    		if (aliens.size() >= 1 && bulletsPlayer.size() >= 1) {
    			for (int i = 0; i < aliens.size(); i++) {
    				for (int i2 = 0; i2 < bulletsPlayer.size(); i2++) {
    					if (aliens.get(i).getBounds().intersects(bulletsPlayer.get(i2).getBounds())) {
    						deadAliens.add(i);
    						deadBullets.add(i2);
    						player.incScore(100 * niveau);
    						shotsHit++;
    						aliensKilled++;
    					}
    				}
    			}
    			for (int i = 0; i < deadAliens.size(); i++) {
    				int x = deadAliens.get(i);
    				System.out.println("aliens : " + deadAliens.get(i));
    				aliens.remove(x);
    			}
    			for (int i = 0; i < deadBullets.size(); i++) {
    				int x = deadBullets.get(i);
    				System.out.println("bullets : " + deadBullets.get(i) + x);
    				bulletsPlayer.remove(x);
    			}
    		}
    		if (bulletsAlien.size() >= 1) {
    			for (int i = 0; i < bulletsAlien.size(); i++) {
    				if (player.getBounds().intersects(bulletsAlien.get(i).getBounds())) {
    					gameOverMenu = true;
    				}
    			}
    		}
    	}

Similar Threads

  1. [ASK]Array required, but java.lang.Object Found
    By vikar in forum Object Oriented Programming
    Replies: 5
    Last Post: July 9th, 2013, 06:56 AM
  2. [SOLVED] Game problem: java.lang.IndexOutOfBoundsException
    By The_pizzaguy in forum What's Wrong With My Code?
    Replies: 6
    Last Post: June 12th, 2013, 01:38 AM
  3. Might be a thread leak problem reading a file into an Array list.
    By rushtonjj in forum What's Wrong With My Code?
    Replies: 4
    Last Post: June 10th, 2012, 06:56 AM
  4. Array List Help - Can't find where problem is!!
    By destructobob in forum What's Wrong With My Code?
    Replies: 5
    Last Post: February 21st, 2011, 11:04 PM
  5. Replies: 1
    Last Post: November 22nd, 2008, 12:32 PM

Tags for this Thread