저는 Java 기반 환경 인 "Processing"에서 프로그래밍 과정을 수강 중입니다. 하나의 과제는 3 개의 버튼 (검정색)을 표시하는 프로그램을 작성하는 것입니다. 버튼을 클릭하면 해당 버튼이 다른 색상 (회색)으로 변경됩니다. 우리는 부울 [] 배열을 사용해야합니다. 내 코드는 다음과 같습니다 :Processing에서 부울 배열로 버튼을 만드는 방법?
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'이 아니라 '0'에서 시작합니다. 'setup' 함수에서는 올바른 것이지만 for 루프에서는 0에서 2 대신 1에서 3까지 반복됩니다. –