This will be the last real math lesson—for a while. Don’t worry, if you’ve stuck with me through what we’ve covered so far, this won’t be that much harder.
We are going to cover a really important concept, though, that will come up in
many more places than just doing math in Java, so please do pay attention.
This time around, we’re going to look at how to evaluate exponents, round
numbers, generate random (well, sort of) numbers, and use constants like pi (3.14…)
and e (2.718…).
First, let’s start with exponents.
Create a new class and set up the main method as before. By now, if you’ve been
practicing by yourself, “public static void main(String[] args)” might be second
nature. If not, don’t be discouraged!
There are a lot of classes that we can actually use really easily in Java. I’ll
give you a hint—System is one of them, and you’ve been System.out.println()-ing
for several articles now, so by now, you’re a natural, and you probably didn’t
bat an eye!
Classes, by convention, start with capital letters: System, MathLesson, and so
on. (Ring any bells? So does String, but that’s an object… hmmm… more on that
later.)
The class you’ve been using is System. System is in the java.lang package—the default
folder, if you will, of classes you get for free with the java language without
having to ask the computer to let you use anything else.
We’ll start by introducing another class in java.lang—the Math
class. It’s really useful, and I encourage you to check out this link: Math (Java
Platform SE 8 ) to see what else it offers.
We’re going to use a few methods from Math:
Math.round takes the double you give it, and returns a long
which has the value of the double, rounded as one would think.
Math.floor evaluates the floor function: it takes in a
double, and, if the double is already equivalent to an integer (say, 10.0), it
just returns it; but if it isn’t (say, 7.321), then it returns the biggest
number less than it. In the case of 7.321, it returns 7.0.
Math.ceil evaluates the ceiling function. When the double is equivalent to an
integer (10.0, for example), it behaves like floor and just returns the double.
Otherwise, it returns the smallest number bigger than the one provided (for 7.321,
it returns 8.0).
Math.pow always takes 2 arguments, since an exponent has two parts: “x to the y”.
This is written as Math.pow(x, y), and the result is a double. Order matters
here: 2 cubed and 3 squared aren’t the same number, so Math.pow(2,3) and Math.pow(3,2)
would return 8 and 9, respectively.
Now, for the first time, we’re going to use something not in
java.lang.
This requires what are called “import” statements, so called because they begin
with “import” and then what you want to use.
We’re going to look at 2 very similar functions in the Random class. For this,
the import is
import java.util.Random.*;
That * means “give me everything that is a direct child of
Random”. If you look at Random
(Java Platform SE 8 ), you can see all the functions that class gives you access
to.
That import statement goes at the very top of your Java file, even above
public class Whatever{
}
When you start writing longer, more complex code, you may
decide not to use something, or you may copy code from somewhere, and need
something extra. Your IDE can surely help you optimize your imports—give you
what you need and remove what you don’t.
Once you write the import statement, you can use whatever you imported.
From Random, we want two specific (similar) functions: one
that generates a (pseudo-)random number with no bound (except that which is
imposed by the int data type—plus or minus about 2 billion) and one that
generates a number bounded by the parameter we pass.
Once you have the import statement written, inside main, you could do something
like—in plain English—“give me a random number” or “give me a random number
less than 28.”
You need to first create a Random object, and you do that
like this:
Random randy = new Random();
“randy” isn’t anything special—it could just be “pepperoniPizza”
or “squidwardsClarinet” or whatever you want.
But let’s look at this line more closely.
First, the initial “Random”. This tells us that whatever object we are creating
is from the Random class. The Random class is great for generating random
numbers, so we’ll use it. “randy” (or “pepperoniPizza,” etc.) is the name of
the Random object. Remember, every variable—primitive or object—has a name, a
type, and a value. Random is its type, and randy is its name.
The keyword “new” tells the computer to find space in memory
to hold a Random object. Random() creates that object—there’s its value!
So, again
Random randy = new Random(); means
Find somewhere in memory where you can put a Random object, create a brand new
one, put it in that space, and name it “randy”.
Classes—like Random—have methods: pre-built pieces of code that do things for
us that we can use because we imported them properly.
You invoke a method with a dot, and with its name and parameters. This is what you
were doing with Math.floor() or Math.ceil or even System.out.println(), but
those didn’t need imports.
Random has two methods that interest us:
- Random.nextInt()
- Random.nextInt(seed)
Let’s wrap up this article by going back to Math.
Math has a few constants pre-defined because they’re so
important. Constants are variables with a name, type, and value, but there’s a
catch: once they’re given a value, it can’t be changed. To differentiate
between constants and regular variables, we give the names of constants in
all-caps, not in camelCase like we would for justAnotherRegularVariable.
You access pi with Math.PI and you access e with Math.E.
Notice now how Math.PI and Math.E are different from, say, Math.floor()
Math.floor() is a method, so it has parameters, so it has parentheses
into which they go. Math.PI, on the other hand, is just the number 3.14… out to
some precision—not a method, so you don’t put parentheses. (Same with Math.E,
which is 2.718… out to some precision.)
Play around with the Math and Random classes! See what
methods are available to you in each one, and see what kinds of errors you get
if you omit the import for Random! Remember, the best way to get good is to
practice!
No comments:
Post a Comment