(Or Maths, if you prefer.)
Adding, Subtracting, etc.
No, 3.0f is not a typo. The f makes 3 a float. You can use lower- or uppercase letters (D means double; F means float; and L means long).
This is where math starts to get tricky. To engage float division (remember from Chapter 3, float is an imprecise number), we need 3 to be a float. If we instead wrote zombies / 3, this would result in integer division, and the remainder would be lost. For example, 32 / 3 is 10.
This gives you the remainder of dividing zombies by four.
More Complex Math
If you want to do anything other than add, subtract, multiply, divide, and modulo, you will have to use the java.lang.Math class. The Math class is part of the Java Development Kit (JDK) which is always available as part of core Java. There are many such classes which we will encounter as we go.
abs: Returns the absolute value of a value
min: The minimum of two numbers
max: The maximum of two numbers
pow: Returns the value of the first argument raised to the power of the second argument
sqrt: Returns the correctly rounded positive square root of a double value
cos: Returns the trigonometric cosine of an angle
sin: Returns the trigonometric sine of an angle
tan: Returns the trigonometric tangent of an angle
For a list of all the methods in Math, see the Java docs.1
Sine If you’re unfamiliar with sine and cosine, they are very useful whenever you want to draw a circle, for example. If you’re on your computer right now and want to learn more about sine and cosine, please look at this animation2 referenced in the footnote at the end of this page and keep watching it until you understand the sine wave.
Random Numbers
The easiest way to create a random number is to use the Math.random() method .
The random() method returns a double value greater than or equal to zero and less than one.
This would result in a random number from 0 to 5. We could then add one to get the numbers 1 to 6. We need to have (int) here to convert the double returned from random() to an int—this is called casting.
nextInt(int n): A random number from 0 to n (not including n)
nextInt(): A random number uniformly distributed across all possible int values
nextLong(): Same as nextInt() but for long
nextFloat(): Same as nextInt() but for float
nextDouble(): Same as nextInt() but for double
nextBoolean(): True or false
nextBytes(byte[] bytes): Fills the given byte array with random bytes
Now you can create random numbers and do math with them. Hurray!
Seeds If you create a Random with a seed (e.g., new Random(1234)), it will always generate the same sequence of random numbers when given the same seed.
Summary
How to add, subtract, multiply, divide, and modulo
Using the Math library in Java
Creating random numbers