SvelterEagle
SvelterEagle

Reputation: 39

Why do I get an Array index out of bounds exception?

Accordin to the debug screen the error is in:

1.Line 16: (Class RandomLevel)

protected void generateLevel() {
    for (int y = 0; y < height; y++) {
        for (int x = 0; y < width; x++) {
            tiles[x + y * width] = random.nextInt(4);   //Here is the error.
        }
    }
}

2.Line 15: (Class Level)

public Level(int width, int height) {
    this.width = width;
    this.height = height;
    tiles = new int[width * height];
    generateLevel();                               //Here is the error.
}

3. Line 10: (Class RandomLevel)

public RandomLevel(int width, int height) {
    super(width, height); // Here is the error.
}

4. Line 43: (Class Game)

public Game() {
    Dimension size = new Dimension(width * scale, height * scale);
    setPreferredSize(size);

    screen = new Screen(width, height);
    frame = new JFrame();
    key = new Keyboard();
    level = new RandomLevel(64, 64);                  // Here is the error.

    addKeyListener(key);
}

5.Line 124: (Class Game)

public static void main(String[] args) {
    Game game = new Game();                           // Here is the error.
    game.frame.setResizable(false);
    game.frame.setTitle(game.title);
    game.frame.add(game);
    game.frame.pack();
    game.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    game.frame.setLocationRelativeTo(null);
    game.frame.setVisible(true);

    game.start();
}

What am I supposed to do? I understand what the exception is, but I dont know why is it appearing. Help?

Upvotes: 1

Views: 131

Answers (3)

adrCoder
adrCoder

Reputation: 3275

you have two errors:

1)

 for (int x = 0; y < width; x++) {

change y to x

2)

tiles = new int[width * height];

but

  tiles[x + y * width] = random.nextInt(4);   //Here is the error.

this will go up to

tiles[width+height*width] 

which will result in an error, change

 tiles = new int[width * height];

to

tiles = new int[width + width * height];

Upvotes: 1

Andrew Stein
Andrew Stein

Reputation: 13150

You have

for (int x = 0; y < width; x++) {

did you intend

for (int x = 0; x < width; x++) {

Upvotes: 1

rgettman
rgettman

Reputation: 178263

Your condition for the inner for loop is wrong.

for (int x = 0; y < width; x++) {

You are looping over x, but your condition involves y again. Try

for (int x = 0; x < width; x++) {

Upvotes: 7

Related Questions