ant c ant c - 7 months ago 11
Java Question

simple message error on else

Hello Overflow community, I am currently making a soundboard that plays sound when you click on a button (first mini project so its quite exciting), and when I try to use an

else
statement in my project I get a compile error. Can anyone tell me what my problem is? I would love to learn why this happened so this wont happen in the future.
I've tried using
else if
but I get a syntax error so I'm lost in what I should be doing.

Here's the problematic part of my code:

void mousePressed(){
if (mouseX > 100 && mouseX < 100 + width
&& mouseY > 100 && mouseY < 100+height)
s2.play();
image(p2,1,1);
} else{ //here is where i get the error
s2.pause();
s2.rewind();
}

Answer

Use proper indentation to really see what's going on:

void mousePressed(){
   if (mouseX > 100 && mouseX < 100 + width && mouseY > 100 && mouseY < 100+height)
      s2.play();

   image(p2,1,1);
} 
else{
  s2.pause();
  s2.rewind();
}

Your if statement does not have an opening curly bracket { after it, so it only evaluates the next line. Then the following closing curly bracket } closes the mousePressed() function. After that you have your else, which doesn't make sense. That's not valid syntax. That's why you get the error.

To fix it, you probably just want to add an opening curly bracket { after your if statement:

void mousePressed(){
   if (mouseX > 100 && mouseX < 100 + width && mouseY > 100 && mouseY < 100+height){
      s2.play();
      image(p2,1,1);
   } 
   else{
     s2.pause();
     s2.rewind();
   }
}