我正在使用Youtube上的教程:
如何制作Java"塔防#34;游戏?第1部分,共3部分! - " Layouting"
编码工作正常,但现在这个错误不断出现
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException
当我运行我的代码时,有人可以帮助我吗?这是我的代码
import java.awt.*;
public class Store {
public static int shopWidth = 8 ;
public static int buttonSize = 32;
public Rectangle[] button = new Rectangle[shopWidth];
public Store() {
define();
}
public void define(){
for(int i=0;1<button.length;i++){
button[i] = new Rectangle((Screen.myWidth/2)-((shopWidth*buttonSize)/2), 10, buttonSize, buttonSize);
}
}
public void draw(Graphics g){
for(int i=0;1<button.length;i++){
g.fillRect(button[i].x, button[i].y, button[i].width, button[i].height);
}
}
}
答案 0 :(得分:1)
这是一个简单的拼写错误。
尝试使用i<button.length
代替1<button.length
...
现在,循环在异常发生之前不会结束。
答案 1 :(得分:0)
您在1<button.length
循环中实施了for
。在这种情况下,1
始终小于button.length
,因为它的长度为shopWidth
,即8,而且您无法在长度为8的数组中存储无限值。
您应该将其写为i<button.length