ArrayIndexOutOfBoundsException的问题

时间:2014-10-16 18:31:45

标签: java arrays

我对java很新,我在这里需要一些帮助:

package com.game.libs;

import java.awt.Graphics;
import java.awt.image.BufferedImage;

public class Animation {

    private int speed = 0; // defines in how many ticks the animation should go to the next frame
    private int amountOfFrames = 0; //amount of frames in the animation
    private int index = 0; //time value used in the method runAnimation()
    private int currentFrameNumber = 0; //the number of the current frame
    private BufferedImage frames[]; //images in the animation
    private BufferedImage currentFrameImage; //current frame's image
    //13 frame animation
    public Animation(BufferedImage[] img, int fps){
        frames = img;
        amountOfFrames = img.length-1;
        speed = 60/fps;
        for (int i=0;i<img.length-1;i++){
            this.frames[i] = img[i];
        currentFrameNumber = 0;
        currentFrameImage = img[0];
        }
    }

    public void runAnimation(){
        index++;
        if(index > speed){
            index = 0;
            nextFrame();
        }   
    }

    public void nextFrame(){
        currentFrameNumber++;
        if(currentFrameNumber > amountOfFrames)
            currentFrameNumber = 1;
        currentFrameImage = frames[currentFrameNumber]; // THIS IS THE LINE WITH THE ERROR
    }

    public void drawAnimation(Graphics graphics, int x, int y, int offset){
        graphics.drawImage(currentFrameImage, x - offset, y, null);
    }

    public void setCurrentFrame(int currentFrame){
        this.currentFrameNumber = currentFrame;
    }

    public int getCurrentFrameNumber(){
        return currentFrameNumber;
    }

    public int getFps(){
        return speed;
    }

    public void setFps(int fps){
        this.speed = 60/fps;
    }

    public void setFrames(BufferedImage[] img){
        this.frames = img;
        amountOfFrames = img.length;
    }

    public BufferedImage[] getFrames(){
        return frames;
    }
}

我得到的错误是数组索引输出边界。在第38行(nextFrame方法,它在代码中) 我之前遇到过这个错误,而且我知道如何(并尝试)修复它但是它说1甚至0都超出范围...... Plox的帮助,我知道这很模糊:(但我试图让我的问题(和代码)清楚。

记住,我是java的新手,有过waaaaaaay更简单的语言/引擎的经验,但了解相当多。

1 个答案:

答案 0 :(得分:1)

请注意,Java数组从0开始编入索引,因此在nextFrame()中将currentFrameNumber重置为1而不是0时,很奇怪(但没有错误)。

此外,使用amountOfFrames来控制迭代计数是非常多余的。通常的Java习语涉及直接使用数组.length,也许

    if(currentFrameNumber >= frames.length) {
        currentFrameNumber = 0;
    }

但这些都没有真正解释你得到的例外,所以必须有更多。

或其它内容:也许抛出异常的类不是从您提供的相同版本的代码中编译的。