2015-03-30 102 views
1

Accordin到的調試屏幕的誤差是在:爲什麼我得到一個數組索引越界異常?

1.Line 16:(類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:(職業等級)

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

3。第10行:(類RandomLevel)

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

4. 43行:(類遊戲)

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:(類遊戲)

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(); 
} 

那我該怎麼辦?我明白什麼是例外,但我不知道它爲什麼出現。幫幫我?

+0

仔細查看此條件爲'(INT X = 0; y <寬度; x ++)',複製粘貼可能會導致問題有時 – 2015-03-30 18:29:13

回答

7

您的內部for循環的條件是錯誤的。

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

您遍歷x,但你的病情再次涉及y。嘗試

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

感謝你,現在我知道im阻滯。謝謝! – SvelterEagle 2015-03-30 18:30:26

1

你有

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

你打算

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

你有兩個錯誤:

1)

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

變化Y到X

2)

tiles = new int[width * height]; 

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

這將上升到

tiles[width+height*width] 

這將導致一個錯誤,改變

tiles = new int[width * height]; 

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