More math!
Computer Science is ALL about math. That's why College Board wants you to know about a few other things you can do with Java in the math realm.
We can use the Math class (built into Java) to utilize some extra methods.
- Absolute Value
- Random Numbers
- Exponents
Absolute Value
Absolute value makes sure that a number is ALWAYS positive. If the number is negative, the absolute value makes it positive if it's already positive, great.
We can use Math.abs() for both ints and doubles to make the number positive.
int x = -100;
int y = 37;
double a = -42.6;
double b = 16.98;
System.out.println(Math.abs(x));
System.out.println(Math.abs(y));
System.out.println(Math.abs(a));
System.out.println(Math.abs(b));
x and a will change, but y and b will stay the same.
Random Numbers
What if we need to create a random number? Maybe it's for dice or a guessing game. There are a few ways to do this.
Method 1
We can use Math.random() to get a random value between 0 and 1. It is exclusive, so don't expect to get 0 or 1.
System.out.println(Math.random());
But what if we want a value between 0 and, for example, 5? (Still exclusive)
We can just multiply the value of Math.random() by 5.
System.out.println(Math.random()*5);
Method 2
The second method allows more control over the range you want a random number from.
int high = 10;
int low = 5;
int random = Math.random(high-low) + low;
System.out.println(random);
In this method, we specify the high and the low. We won't get the high as it is exclusive. But we will get the low, as it is inclusive.
The expression we wrote will get a random number between high and low, or 10 and 5.
Exponents
And finally, exponents. Exponents are very easy to do. We just use Math.pow().
int base = 2;
int exponent = 4;
System.out.println(Math.pow(base,exponent));
You will see that base is cast to a double if you run this. That's because Math.pow() really only accepts double, but will work with int. Just know it will convert it to a double.
However, this code WILL NOT work:
int base = 2;
int exponent = 4;
int calc = Math.pow(base,exponent);
System.out.println(calc);
You cannot put a double in an int without casting.