package api_demo;/*
* random类用来生成随机数字,使用步骤:
* 1、导包
* 2、创建
* 3、使用
* */import java.util.Random;publicclassdemo_random{publicstaticvoidmain(String[] args){
Random r =newRandom();// 随机获取一个int数字// 1、不带参数,在所有整数范围内产生随机数。int num = r.nextInt();
System.out.println("不带参数产生的随机数是:"+num);// 2、带参数,产生0到int-1范围内的随机数int num1 = r.nextInt(10);
System.out.println("带参数产生的随机数是:"+num1);}}
"C:\Program Files\Java\jdk-14.0.1\bin\java.exe""-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2020.1\lib\idea_rt.jar=6894:C:\Program Files\JetBrains\IntelliJ IDEA 2020.1\bin"-Dfile.encoding=UTF-8-classpath C:\Users\Jinfanglin\IdeaProjects\javaSe\out\production\javaSe api_demo.demo_random
不带参数产生的随机数是:1253518504
带参数产生的随机数是:5
Process finished with exit code 0
package api_demo;/**
*
* 根据int类型的变量n,生成范围为1-n的随机数字.
*
*/import java.util.Random;import java.util.Scanner;publicclassrandom_lianxi1{publicstaticintnewRandom(int n){
Random r =newRandom();return r.nextInt(n)+1;}publicstaticvoidmain(String[] args){
Scanner sc =newScanner(System.in);int num = sc.nextInt();for(int i =0; i <5; i++){
System.out.println(newRandom(num));}}}
"C:\Program Files\Java\jdk-14.0.1\bin\java.exe""-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2020.1\lib\idea_rt.jar=7240:C:\Program Files\JetBrains\IntelliJ IDEA 2020.1\bin"-Dfile.encoding=UTF-8-classpath C:\Users\Jinfanglin\IdeaProjects\javaSe\out\production\javaSe api_demo.random_lianxi1
444241
Process finished with exit code 0