Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Causing Unexpected Errors

Tags:

java

I'm having a problem with some code, in the constructor of the level, i have this.public

Level(int width, int height, String level) {
    grid=new Block[width][height];
    String v = "";
    for (int y = 0; y < height; y++) {
        for (int x = 0; x < width; x++) {
            char s = level.charAt(y * height + x);
            if (s=='#') {
                grid[x][y] = new Wall(x, y);
            } else if (s=='_'){
                grid[x][y] = new Block(x, y);
            }
        }
    }
}

Only when I run the Level initializer with the following...

              new Level(16,16,"###############" +
                              "#_____________#" +
                              "#___######____#" +
                              "#___#____###__#" +
                              "#___#__###_#__#" +
                              "#####_________#" +
                              "#_____#__######" +
                              "#___###_______#" +
                              "#_#_#_# #####_#" +
                              "#_#___#____#__#" +
                              "#_#####__###_##" +
                              "#_____####____#" +
                              "#_#_#______##_#" +
                              "###_#__#####__#" +
                              "#___#______#__#" +
                              "###############");

I get

    Exception in thread "main" java.lang.StringIndexOutOfBoundsException: 
    String Index out of range: 240
at java.lang.String.charAt(String.java:686)
at Level.<init>(Level.java:17)
at Game.<init>(Game.java:12)
at Main.main(Main.java:7)`

Any help is greatly appreciated.

like image 885
Barakados Avatar asked Apr 23 '26 09:04

Barakados


1 Answers

Your grid is 16 * 15 (and hence the exception while calculating char position)

[EDIT] modify you formula

char s = level.charAt(y * width + x);
like image 58
Mitesh Pathak Avatar answered Apr 24 '26 21:04

Mitesh Pathak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!