1、问题:Java获取随机数
2、思路:
有两种方法:
①通过时间(毫秒数)来获取
②Math.random();获取一个double类型的随机数,取值范围是[0,1)
3、代码:
①
/**
* 获取随机数
* @author 晴澜
* @version 2023.03.16
*/
public class Random {
public static void main(String[] args) {
//通过时间来获取
//System.currentTimeMillis();得到一个long类型的时间
//表示的是从1970年1月1日00:00:00开始计算,到当前时间为止,一共经历的毫秒数
long time = System.currentTimeMillis();
int num = (int)(time%10);
System.out.println(num);
}
}
②
/**
* 获取随机数
* @author 晴澜
* @version 2023.03.16
*/
public class Random {
public static void main(String[] args) {
// Math.random();获取一个double类型的随机数,取值范围是[0,1)
double num = Math.random();
System.out.println(num);
// 想要获取0-9之间的任意的随机整数
int num2 = (int)(Math.random()*10);
System.out.println(num2);
//想要获取[a,b]随机整数
//(int)(Math.random()*(b-a+1))+a ===> [a,b]之间的随机整数
}
}
以上就是获取随机数的全部内容,有问题私信我!
长风破浪会有时,直挂云帆济沧海。