user1215307
user1215307

Reputation: 5

Syntax error on if else statement

I'm just writing a basic code that takes 2 inputs and an operator and solves. I have to code the program to tell it to not let a division of 0 happen but I my else keeps having an error message saying that there is a syntax error token. I'm not sure why because I have done if else statements in the past and it doesn't look any different. I am new at programming. Help would be appreciated

 if((operator == '/') && (operand2 == 0))
   JOptionPane.showMessageDialog(null,"Division by 0 not allowed"); 
   System.exit(0);
 else 
  add = operand1 + operand2;
  mult = operand1 * operand2; 
  sub = operand1 - operand2;
  div = operand1 / operand2;
  remainder = operand1 % operand2;

Upvotes: 0

Views: 1829

Answers (3)

brandonio21
brandonio21

Reputation: 85

As the others before me have stated, yes, you need to have curly braces surrounding your if statement bodys when they are more than one line. Java pretty much only sees this part of your code.

if((operator == '/') && (operand2 == 0))
  JOptionPane.showMessageDialog(null,"Division by 0 not allowed"); 
else 
  add = operand1 + operand2;

Now, however, if you were to add curly braces {} to your if and else blocks, Java would be able to read the whole code. It looks something like this

if((operator == '/') && (operand2 == 0))
{
 JOptionPane.showMessageDialog(null,"Division by 0 not allowed"); 
 System.exit(0);
}
else
{ 
 add = operand1 + operand2;
 mult = operand1 * operand2; 
 sub = operand1 - operand2;
 div = operand1 / operand2;
 remainder = operand1 % operand2;
}

Upvotes: 0

darren102
darren102

Reputation: 2830

You need to have curly braces { } around the if and the else if there are more than one line of code under them. This is the reason you are having the issue

Upvotes: 1

casablanca
casablanca

Reputation: 70701

If you have more than one statement within a block, you need to surround it with braces:

if (...) {
  ...
} else {
  ...
}

Upvotes: 5

Related Questions