package demo.api;
import org.junit.Test;
import java.util.Random;
class MathAndRandom {
@Test
public void testMathAndRandom() {
System.out.println("取绝对值:" + Math.abs(-3));
System.out.println("向上取整:" + Math.ceil(3.14));//返回double类型 4.0
System.out.println("向下取整:" + Math.floor(-3.14));//返回double类型 -4.0
System.out.println("四舍五入:" + Math.round(3.54));//返回int类型 4
System.out.println("随机数:" + Math.random());// 0 <= Math.random() < 1.0 伪随机数
char[] arr = {'a', 'b', 'c', 'd', 'e', 'f'}; //length == 6
Random r1 = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 4; i++) {
int index = r1.nextInt(arr.length); //产生0~5的随机数 int类型(还可生成Boolean Double 0~1 Float 0~1 Long类型)
sb.append(arr[index]);
}
System.out.println("随机验证码:" + sb);
for (int i = 0; i < 10; i++) {
System.out.println(r1.nextInt());
// System.out.println(r1.nextLong());
// System.out.println(r1.nextDouble());
}
}
}
Math类和Random类常用方法
最新推荐文章于 2022-06-15 12:10:43 发布