JAVA 基础笔记----Random类的使用

/*
 * Random类用来生成随机数。
 *
 * 使用:
 * 1.int num = r.nextInt(),生成int范围内的随机整数。
 * 2.int num = r.nextInt(3),生成[0,3)内的随机整数
 * */
public class demo03 {
    public static void main(String[] args) {
        Random r = new Random();

        //生成int范围内随机数
        int num = r.nextInt();
        System.out.println("随机数:" + num);

        //生成[0,10)随机数
        System.out.println("随机数:" + new Random().nextInt(10));

        //生成[1,10]随机数
        System.out.println("随机数:" + (new Random().nextInt(10)+1));

    }
}

//内容参考B站视频
/*
* Random与Scanner练习
* 随机数猜测
* */
public class demo04 {
    public static void main(String[] args) {
        //设置随机数边界:[0,10]
        int num = new Random().nextInt(11);
        //创建键盘输入类
        Scanner sc = new Scanner(System.in);
        do {
            System.out.print("请输入你猜的随机数:");
            //输入随机数
            int input = sc.nextInt();
            //判断
            if(input > num) System.out.println("你猜的数太大了!");
            else if (input < num) System.out.println("你猜的随机数太小了!");
            //输入数与随机数相等时跳出循环
            else break;
        } while(true);
        System.out.println("恭喜你,猜对了!");
        System.out.println("随机数是:"+ num);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值