gpt4 book ai didi

java - 导致意外错误的字符串

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:47:53 26 4
gpt4 key购买 nike

我的一些代码有问题,在关卡的构造函数中,我有 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);
}
}
}
}

仅当我使用以下...运行级别初始化器时......

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

我明白了

    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)`

非常感谢任何帮助。

最佳答案

您的网格是 16 * 15(因此在计算 char 位置时出现异常)

[EDIT]修改你的公式

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

关于java - 导致意外错误的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21059809/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com