# Thread: Beginner - question of 'if' statement

1. Senior Member
Join Date
Oct 2010
Posts
119
Rep Power
0

## Beginner - question of 'if' statement

so im trying to prevent a division by zero error with an if statement, and im wondering if i can use one if statement or if i need two.

im doing a gas mileage calculator, i have got everything done up to the calculation. what im wondering is if i can doing something like this or not:

Java Code:
```if (totalmilescounter != 0, totalgallonscounter != 0)
{
//calulate gas mileage
MPG = totalmilescounter / gallonscounter;
} //end if```

2. You can divide any number by any other number as long as that any other number isn't zero:

Java Code:
```if (anyOtherNumber != 0)
result= anyNumber/anyOtherNumber;```
kind regards,

Jos

3. Senior Member
Join Date
Dec 2009
Posts
104
Rep Power
0
Try and compile it.
Add an else statement and you can see for yourself if it works.

4. Senior Member
Join Date
Oct 2010
Posts
119
Rep Power
0
Originally Posted by JosAH
You can divide any number by any other number as long as that any other number isn't zero:

Java Code:
```if (anyOtherNumber != 0)
result= anyNumber/anyOtherNumber;```
kind regards,

Jos

sorry for the delay in getting back to you, your comment took care of it, i only needed to put one of the items into the if in order to avoid the "divide by 0" issue. thanks!

5. Member
Join Date
Sep 2010
Location
Qc
Posts
31
Rep Power
0
To test multiple field in an if statement you can do it that way:

Java Code:
```if (someVar != 0 && someOther == 0)
...```
you could also do:

Java Code:
```if (someVar != 0 || someOther == 0)
...```
&& means AND
|| means OR

-> "if varA == 0 && varB == 0" Both condition must be met to enter the if.
-> "if varA == 0 || varB == 0" Either condition must be met to enter.

There are several other comparison "keywords" you can use.

6. Senior Member
Join Date
Oct 2010
Posts
119
Rep Power
0
Jack, thank you for this reply, i was wondering if there was some sort of connector to test for 2 things in the if statement, i tried a comma separating them, a semicolon, tried parenthesis numerous different ways too. Im glad to know that the && or || will work, i will definitely need that in the future! thanks.

7. Member
Join Date
Sep 2010
Location
Qc
Posts
31
Rep Power
0
You can put as many test as you want using different comparison.

Here's something I use. Not complicated, but just to show.

Java Code:
```if (xyz.x <= t.topRightCorner.x &&
xyz.x >= t.botLeftCorner.x &&
xyz.y <= t.topRightCorner.y &&
xyz.y >= t.botLeftCorner.y &&
xyz.z <= t.topRightCorner.z &&
xyz.z >= t.botLeftCorner.z) {```
The above will test if each of the coordinates xyz.x, xyz.y and xyz.z are smaller or equal than/bigger or equal than topRightCorner/botLeftCorner.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•