Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java BoundsException的固定排列_Java_Arrays_For Loop_Indexoutofboundsexception_Pixels - Fatal编程技术网

Java BoundsException的固定排列

Java BoundsException的固定排列,java,arrays,for-loop,indexoutofboundsexception,pixels,Java,Arrays,For Loop,Indexoutofboundsexception,Pixels,这里我要做的是使用if语句来测试像素y位置是否大于或等于y轴的大小。如果是的话。打破for循环,但是我仍然得到了BoundsException的ArrayOutOfBoundsException。在处理循环时,我应该如何使用break函数 public void render() { counter++; if (counter % 100 == 0) { time++; } for (int y = 0; y < HEIGHT; y++)

这里我要做的是使用if语句来测试像素y位置是否大于或等于y轴的大小。如果是的话。打破for循环,但是我仍然得到了BoundsException的ArrayOutOfBoundsException。在处理循环时,我应该如何使用break函数

public void render() {
    counter++;
    if (counter % 100 == 0) {
        time++;
    }

    for (int y = 0; y < HEIGHT; y++) {
        if (y >= HEIGHT - 10) break;
        for (int x = 0; x < WIDTH; x++) {

            pixels[time + time * WIDTH] = 0xff00ff;
        }

        if (y >= HEIGHT - 1) break;

    }

}
public void render(){
计数器++;
如果(计数器%100==0){
时间++;
}
对于(int y=0;y=高度-10)中断;
对于(int x=0;x=高度-1)中断;
}
}

有时通过
时间+时间*宽度计算的值大于或等于
像素中的元素数量

pixels[time + time * WIDTH] = 0xff00ff;

如果我理解您的代码,您不会更改循环中的时间,因此您可能应该将时间+时间乘以x或y(而不是宽度),因为宽度是常量。

要详细说明Johannes的答案,您计算到像素数组中的索引不正确。由于
time
的值在
render()
方法之外初始化,但每次调用
render()
方法时,该值都会递增,因此对
time+time*WIDTH
的计算可能不会产生所需的结果。假设最初将
time
设置为0,则在调用
render()
HEIGHT
次后,将出现AOOB异常

你可能想写的是

for (int y = 0; y < HEIGHT; y++) {
    for (int x = 0; x < WIDTH; x++) {
        pixels[x + y * WIDTH] = 0xff00ff;
    }
}
for(int y=0;y

假定您的像素数组的大小至少为
宽度
x
高度
,则不会出现AOOB异常。

请在线程“thread-2”java.lang.ArrayIndexOutOfBoundsException:48762 at com.game.graphics.Screen.render(Screen.java:38)中发布您的exception的完整堆栈跟踪在com.game.game.render(game.java:101)在com.game.game.run(game.java:81)在java.lang.Thread.run(Thread.java:745)请将异常的完整堆栈跟踪很好地格式化为您的问题。文件Screen.java的第38行是哪一行?