11. java random类

一、random类使用

import java.util.Random;

public class Demo{
    public static void main(){
        Random r = new Random();
         // 获取一个随机int数字(范围int所有范围)nextInt
        int num = r.nextInt();
        System.out.println(num);
        
        // 获取一个指定范围的随机int数字(左闭右开)nextInt(10)
        //[0, 9)
        for(int i = 0; i < 100; i++){
            int num = r.nextInt(10);
            System.out.println(num);
        }
        
        // 获取[1,n];  100.fori回车
        for(int i = 0; i < 100; i++){
            int num = r.nextInt(n) + 1;
            System.out.println(num);
        }
        
    }
}
// 猜数字小游戏;产生一个随机数后,就不能变了
import java.util.Random;
import java.util.Scanner;

public class Demo{
    public static void main(){
        Random r = new Random();
        // [1-100]
        int randomNum = r.nextInt(100) + 1;
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入你的猜测:");
        int guessNum = sc.nextInt();
        
        while(true){
            if(guessNum > randomNum){
                System.out.println("太大了");
            }else if(guessNum < randomNum){
                System.out.println("太小了");
            }else{
                System.out.println("对了");
                break;
            }
        }
        System.out.println("游戏结束");
    }
}
package china.java.demo;

import java.util.Random;
import java.util.Scanner;

public class Demo01 {
    public static void main(String[] args) {
        Random rd = new Random();
        int randomNum = rd.nextInt(100) + 1;
        // 猜10次
        for (int i = 0; i < 10; i++) {
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入你的猜测:");
            int guessNum = sc.nextInt();
            if (guessNum > randomNum) {
                System.out.println("太大了");
            } else if (guessNum < randomNum) {
                System.out.println("太小了");
            } else {
                System.out.println("对了");
                break;
            }

        }

    }
}

你可能感兴趣的:(11. java random类)