与ArrayIndexOutOfBoundsException异常
问题我是很新的Java和我将在这里需要一些帮助:与ArrayIndexOutOfBoundsException异常
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更容易的语言/引擎的经验,但了解相当多的
请注意,Java数组索引是从0开始,所以很奇怪(但不是错误的),在nextFrame()
您重置currentFrameNumber
1而不是0,当它运行在。
另外,使用amountOfFrames
来控制迭代次数非常多。通常的Java成语涉及使用数组.length
直接,也许
if(currentFrameNumber >= frames.length) {
currentFrameNumber = 0;
}
无的真正解释了你,虽然异常,因此必须有更多的东西。
或者别的什么东西:也许抛出异常的类不是从你提供的代码的相同版本编译而来的。
是的,这是一个错误,我已经改变了我的问题,第38行甚至没有'runAnimation()'方法 – user3837761 2014-10-16 18:51:44
更新了我的答案。其中大部分仍然相关。 – 2014-10-16 19:34:14
它当然是!谢谢 – user3837761 2014-10-16 19:51:23
'setFrames'方法中'amountOfFrames = img.length;'也应该是'amountOfFrames = img.length-1;'。 – Tom 2014-10-16 18:38:34
通过了解堆栈跟踪,您已经领先于该包。对于数组边界来说,要记住的重要一点是数组的原点为零,因此两个元素的数组只有元素0和1。当然,具有零元素的数组甚至没有元素0。你对'currentFrameNumber'的检查可能应该是'> ='vs'>',也许应该重置为零。 – 2014-10-16 18:44:51
@Tom应该吗? “img”中的元素数量不等于元素**为**帧的帧数 – user3837761 2014-10-16 18:46:37