我在这里尝试做的是使用if语句来测试像素y位置是否大于或等于y轴的大小。如果是。打破for循环,但我仍然得到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;
}
}
答案 0 :(得分:0)
有时time + time * WIDTH
计算的值大于或等于pixels
答案 1 :(得分:0)
pixels[time + time * WIDTH] = 0xff00ff;
如果我理解你的代码,你不会改变循环中的时间,所以你可能应该将时间+时间乘以x或y(而不是WIDTH),因为WIDTH是常量。
答案 2 :(得分:0)
To elaborate on Johannes answer, you are calculating the index into the pixel array incorrectly. Your calculation of time + time * WIDTH
will likely not yield your desired results, as the value of time
is initialized outside the render()
method, but it is incremented every time the render()
method is called. Assuming time
is set to 0 initially, then you will get an AOOB exception after you have called render()
HEIGHT
times.
What you probably meant to write was
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
pixels[x + y * WIDTH] = 0xff00ff;
}
}
Presuming your pixels array is at least WIDTH
x HEIGHT
in size then this will not have an AOOB exception.