3

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.

2 Answers 2

4

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

[EDIT] modify you formula

char s = level.charAt(y * width + x);
Sign up to request clarification or add additional context in comments.

2 Comments

Ah my bad. Thanks so much for catching that.
yep also to be on safer side I will always pass height as first arg and then width to my func....
1

Also,

char s = level.charAt(y * height + x);

should probably be

char s = level.charAt(y * width + x);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.