Continuing on from the last article, in this one, we’ll still be doing math. You can keep working out of MathLesson, or you can, in another file, create AnotherMathLesson or the like.
You should set the new class up just as we have before, with the class name and
file name matching, and with
public static void main(String[] args){
}
inside of the class.
Last time, we covered addition, subtraction, division, multiplication, modulus,
increment, and decrement. Take a few minutes to review them before moving on.
Now, we’re going to look at a few more operations, starting
with strict inequalities.
Comparing if something is greater than is easy. Inside main, one could write:
int x = 6;
Int y = 7;
boolean isYBigger = y > x;
Again, in plain English, this code snippet first creates and
initializes to 6 and 7 x and y, then creates a Boolean to store the answer to
the question “is y greater than x?” (Yes, so if you were to print isYBigger,
you would see true on your screen.)
comparing with less-than works exactly the same way, except we use the opposite
symbol, <.
The thought process is the same: initialize the numbers you want to compare and
the Boolean to store the answer, and then compare them with <, assigning the
result of the comparison to the Boolean.
Loose inequality (i.e., greater than [or less than]-or-equal-to) works very
similarly. We just don’t have a single key for “greater-than-or-equal-to” or “less-than-or-equal-to”,
so we use >= and <= instead.
It's perfectly reasonable to want to check if something is anything
but exactly equal and for that, we have a “not-equal” operator,
which is !=
Get used to seeing ! in Java—because anytime you need to
negate a Boolean expression, this is how it’ll happen.
if I have a Boolean isTuesday that is true on Tuesdays and false every other
day of the week, then !isTuesday is the same as having another variable,
isNotTuesday, that is true six days a week and false on Tuesdays.
You can combine mathematical operations with the assignment
operator. You can say “x gets the result of x plus y” or “x gets the result of
x times y” or something similar, in this way:
x+=y;
This means “x gets the result of x plus y”
x*=y;
This means “x gets the result of x times y”
x-=y;
This means “x gets the result of x minus y”
x/=y;
This means “x gets the result of x divided by y”
x%=y;
This means “x gets the result of x mod y” (remember, “mod” means “the remainder
when divided by some given number”)
You could, just as validly, write y+=x (but then be careful,
because the sum is being stored in y, not in x.)
No comments:
Post a Comment