1. Math&Random
1.1. Math
java.lang.Math
是jdk中提供的一个用于数学类相关运算的类,内部的所有方法全部都是static
方法,Math内部将默认构造器私有化,因此无法直接实例化;
Math内部只提供了常量以及静态方法:
-
常量
/** *自然对数的基数 */ public static final double E = 2.7182818284590452354; /** * 圆周率 */ public static final double PI = 3.14159265358979323846;
-
常见静态方法
//获取绝对值 System.out.println(Math.abs(-100)); //向上取整(double值) System.out.println(Math.ceil(105.0/10)); //向下取整(double) System.out.println(Math.floor(109.0/10)); //获取两个数值的最大值 System.out.println(Math.max(10, 100)); //获取两数的最小值 System.out.println(Math.min(10, 100)); //计算两数相乘 System.out.println(Math.multiplyExact(10,10)); //计算两数相减 System.out.println(Math.subtractExact(100, 10)); //计算两数相加 System.out.println(Math.addExact(100, 10)); //获取一个数值的指定次幂 System.out.println(Math.pow(2,4)); //获取从0.0~1.0之间随机数 System.out.println(Math.random()); //四舍五入(返回值是整数) System.out.println(Math.round(3.54));
1.2. Random
通过观察Math.random()
方法的实现,发现该方法借助于java.util.Random
类实现的随机数获取,Random
类提供了对于各种数据类型的随机值的获取方法:
nextBoolean()
nextInt()
nextDouble()
nextLong()
Random r = new Random();
//获取随机boolean值
System.out.println(r.nextBoolean());
System.out.println(r.nextDouble());
System.out.println(r.nextInt());
System.out.println(r.nextLong());
//随机获取0~9整数
for (int i = 0; i < 100; i++) {
System.out.println(r.nextInt(10));
}
1.3. 随机数案例-验证码生成器
public class VerifyCodeGen {
//ctrl+shift+u 大小转换快捷键
private static final String base="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static Random random = new Random();
/**
* 生成一个指定长度的验证码
* @param len
* @return
*/
public static String genCode(int len){
char[] codes = new char[len];
for (int i = 0; i < len; i++) {
// 随机索引
int index = random.nextInt(base.length());
//获取指定位置的字符
char c = base.charAt(index);
//将字符存储到数组中
codes[i] = c;
}
//将字符数组转换为String对象
return new String(codes);
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(genCode(8));
}
}
}