Java获取随机整数的两种方法

时间:2024-03-07 18:45:45

方式一:

 

举例:获取 0~3 范围内(包括 0 和 3 )的 int 类型的随机数

Random random = new Random();
System.out.println(random.nextInt(4)); //注意:这里的 4 指 0 1 2 3 四个数

 

方式二:
使用 Math 类的 random 方法

举例:
/**

* 从键盘输入一个范围 [start,end], 获取该范围内的随机数。 注:[1, 5) 表示“左开右闭”,即: 1~5 包含 1,不包含 5


1
* (int)(Math.random() * (end - start + 1) + start); 2 * @author Rsbry 3 */ 4 public class GetRandomNumber { 5 6 public static void main(String[] args){ 7 Scanner input = new Scanner(System.in); 8 System.out.println("请输入取数范围(回车确认)"); 9 System.out.print("首:"); 10 int start = input.nextInt(); 11 System.out.print("尾:"); 12 int end= input.nextInt(); 13 System.out.print("十个随机数:"); 14 for(int i = 0; i < 10; i++){ 15 System.out.print(getRandom(start, end) + "\t"); //输出十个随机整数 16 } 17 } 18 19 public static int getRandom(int start, int end){ 20 return (int)(Math.random() * (end-start+1) + start); 21 } 22 23 }

 

输出结果:

请输入取数范围(回车确认)
首:52
尾:100
十个随机数:75 64 88 58 75 60 71 54 59 87

相关文章