Java常用类的使用:BigInteger、BigDecimal、Random。
BigInteger
、BigDecimal
和Random
是Java中常用的类,用于处理大整数
、高精度小数
和生成随机数
。
1. BigInteger
用于表示任意精度的整数
。
常用方法
add(BigInteger val)
: 将当前BigInteger与指定BigInteger相加。multiply(BigInteger val)
: 将当前BigInteger与指定BigInteger相乘。subtract(BigInteger val)
: 将当前BigInteger减去指定BigInteger。divide(BigInteger val)
: 将当前BigInteger除以指定BigInteger。
代码如下:
import java.math.BigInteger;
public class BigIntegerExample {
public static void main(String[] args) {
BigInteger num1 = new BigInteger("12345678901234567890");
BigInteger num2 = new BigInteger("98765432109876543210");
BigInteger sum = num1.add(num2);
BigInteger product = num1.multiply(num2);
System.out.println("Sum: " + sum);
System.out.println("Product: " + product);
}
}
2. BigDecimal
用于表示任意精度的小数。
常用方法:
add(BigDecimal val)
: 将当前BigDecimal与指定BigDecimal相加。multiply(BigDecimal val)
: 将当前BigDecimal与指定BigDecimal相乘。subtract(BigDecimal val)
: 将当前BigDecimal减去指定BigDecimal。divide(BigDecimal val)
: 将当前BigDecimal除以指定BigDecimal。
代码如下:
import java.math.BigDecimal;
public class BigDecimalExample {
public static void main(String[] args) {
BigDecimal num1 = new BigDecimal("123.456");
BigDecimal num2 = new BigDecimal("987.654");
BigDecimal sum = num1.add(num2);
BigDecimal product = num1.multiply(num2);
System.out.println("Sum: " + sum);
System.out.println("Product: " + product);
}
}
3. Random
用于生成伪随机数。
常用方法:
nextInt(int bound)
: 返回一个大于等于0且小于bound
的随机整数。nextDouble()
: 返回一个0.0到1.0
之间的随机双精度浮点数。
代码如下:
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
Random random = new Random();
int randomInt = random.nextInt(100); // 生成0到99之间的随机整数
double randomDouble = random.nextDouble(); // 生成0.0到1.0之间的随机双精度浮点数
System.out.println("Random Integer: " + randomInt);
System.out.println("Random Double: " + randomDouble);
}
}
上一篇 Java——TreeMap、Properties的使用。 |
欢迎点赞、收藏、评论!!!
| 下一篇 java的变量类型大全。 |