Math and related classes

Math is a class related to math in java. Located under the java.lang package.

Math's constructor is private, and we cannot call it directly to create objects.

Moreover, the attributes and methods in Math are static, and there is no need to create objects.

Common methods to understand through API documentation.

It is worth mentioning that there is a random () method in Math, which returns a random number in the range [0-1).

But if we want a random number between 0-9, then it can be like this, int value = (int) Math.random () * 10;

If you want a random decimal between 5.0-10.9, you can do this, (Math.random () * 6) +5, the range of random () is 0-0.99999 ... then the range is (0.0-5.999994 ...) +5

However, I found a problem that the precision may be lost when calculating decimals.

  At this time, you can consider another Random class that deals specifically with random numbers.

Some commonly used methods,

Random r = new Random ();
r.nextInt (); Randomly generate integers of int type value range, with negative numbers and positive numbers.

r.nextInt (10); With parameters, you can specify the range, an integer between [0-10), including 0 can not get 10, left closed and right open.

r.nextFloat (); randomly generate a decimal of (0.0-1.0)

r.nextBoolean (); randomly generate true and false

and many more.

It can be done by taking a random number of 5.0-10.9, float f = (r.nextInt (6) +5) + r.nextFloat (); [0.0--5.0] +5-> [0.0--10.0] + [ 0.0--0.9999 ..) ie [5.0--10.999 ..)

  UUID class

UUID uuid = UUID.randomUUID (); // Create an object
System.out.println (uuid.toString ()); // Randomly generate a 32-bit each digit is hexadecimal, generally used as the primary key of the table

  BigInteger class

Do you have any questions about the basic data type we are learning, the largest value range is long -2 to the 63rd power to 2 to the 63rd power -1. Then what if we need to exceed the value of this range.

At this time, you can consider the BigInteger class, which is a dynamic array used at the bottom of the class, in short.

Located in the java.math package, inheriting the Number class, the construction methods it provides are all parameters, we generally take String parameters for construction

// Example, design a method to calculate factorial, if this number is too large, long may not be saved, 5: 1x2x3x4x5 120 
	private static BigInteger factorial (int num) { 
		BigInteger result = new BigInteger ("1"); 
		for (int i = 1; i <= num; i ++) { 
			result = result.multiply (new BigInteger (i + "")); 
		} 
		
		return result; 
	}

  If the num parameter is passed a 25, then you will find that the result is far beyond the range of long.

Guess you like

Origin www.cnblogs.com/hebiao/p/12730207.html