【发布时间】:2014-09-29 19:18:08
【问题描述】:
我正在学习在基于 Java 的环境“处理”中的编程课程。一项任务是编写一个显示 3 个按钮(黑色)的程序。单击按钮时,该按钮应更改为另一种颜色(灰色)。我们需要使用 boolean[] 数组。我的代码如下:
boolean[] button = new boolean[3];
void setup(){
size(300,300);
button[0] = false;
button[1] = false;
button[2] = false;
}
void draw(){
int x = (width/(button.length+1));
int y = height/2;
int ellipseSize = 50;
int radius = ellipseSize/2;
background(255);
noStroke();
fill(0);
for(int i = 1; i <= button.length; i++){
ellipse(i*x, y, ellipseSize, ellipseSize);
}
}
//shifting array values upon mouse pressing
void mousePressed(){
int x = (width/(button.length+1));
int y = height/2;
int ellipseSize = 50;
int radius = ellipseSize/2;
for(int i = 1; i <= button.length; i++){
button[i] = !button[i];
if (mouseX > i*x-radius && mouseX < i*x+radius && mouseY > y-radius && mouseY < y+radius){
if (button[i]){
fill(150);
}
}
else {
fill(0);
}
ellipse(i*x, y, ellipseSize, ellipseSize);
}
}
我收到一条错误消息“ArrayIndexOutOfBoundsException: 3”。有人可以帮忙吗?
【问题讨论】:
-
在大多数编程语言中,数组从
0开始,而不是像现实生活中的1。您在setup函数中已经做到了这一点,但在您的 for 循环中却没有,它从 1 循环到 3 而不是 0 到 2。
标签: java arrays button boolean processing