Java Reference
In-Depth Information
We'll need to use float s in just a minute to play a sound effect, because that's
what Canary requires to set the volume and pitch of the sound. And in gen-
eral you might need a floating-point number more often than you think.
For example, let's look at a simple division problem. In Java, you write division
using the “ / ” character (instead of ÷), so to divide the number 5 in half you'd
write 5/2 . Depending on how you do the division, though, the answer might
surprise you.
•5 / 2 is 2 (just 2, nothing more)
•But 5 / 2.0 is 2.5, as you would expect
•5.0 / 2.0 is also 2.5
Why is 5 divided by 2 equal to only 2? On a math quiz, that would be wrong.
But we're not dividing real numbers here; we're dividing int numbers, so the
result is another whole number; another int . There are no fractions at all.
If you want the answer to include fractions, then at least one of the numbers
involved has to have a fractional part. That's why 5 divided by 2.0 (note the
extra .0) gives us the real answer of 2.5 (two and a half). This time, we're using
an int (5) and a double (2.0).
Sometimes you won't care about fractional parts or remainders (leftovers). If
you're calculating something that doesn't have fractional parts, then all- int
math is just fine. Half of a Player or a Cow doesn't make sense (unless you're
making hamburger). But if you need fractional answers, then at least one of
the numbers involved has to be a double or a float .
Here's a handy list of several of the common math operators you might need:
+
Subtraction:
-
Multiplication:
*
Division:
/
They work just as you'd expect, but there are some handy shortcuts.
int health = 50;
health = health + 10;
is the same as
int health = 50;
health += 10; // Same thing
Both result in health being set to 60.

Search WWH ::

Custom Search