zoukankan      html  css  js  c++  java
  • java基础---14. Random

    1 Random概述和基本使用

    import java.util.Random;
    /*
    Random用来生成随机的数字:
    1. 导包
    import java.util.Random;
    2. 创建
    Random r = new Random();
    3. 使用
    获取一个int型随机数字(范围是int所有范围 正负都有): int num = r.nextInt()
     */
    public class Demo01Random {
        public static void main(String[] args) {
            Random r = new Random();
    
            int num = r.nextInt();
            System.out.println("随机数是:" + num);
        }
    }
    

    2 Random生成指定范围内的随机数

    import java.util.Random;
    public class Demo02Random {
        public static void main(String[] args) {
            Random r = new Random();
            for(int i = 0; i < 100; i++) {
                int num = r.nextInt(10);
                //int num = r.nextInt(10);r的范围是[0,10)
                System.out.println(num);
            }
        }
    }
    

    3 Random练习1

    /*
    要求:根据int变量n的值,来获取随机数字,范围是[1,n]
     */
    import java.util.Random;
    public class Demo03Random {
        public static void main(String[] args) {
            int n = 5;
            Random r = new Random();
            for(int i = 0; i < 100; i++) {//打印100个处于[1,5]范围的随机数
                int result = r.nextInt(n) + 1;
                System.out.println(result);
            }
        }
    }
    

    4 Random练习2

    /*
    用代码模拟猜数字小游戏:采用二分法来猜
     */
    import java.util.Random;
    import java.util.Scanner;
    
    public class Demo04RandomGame {
        public static void main(String[] args) {
            Random r = new Random();
            int randomNum = r.nextInt(100) + 1;//[1,100]
            Scanner sc = new Scanner(System.in);
    
            while(true) {
                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;
                }
            }
        }
    }
    
  • 相关阅读:
    groovy main method is use static main(args) //ok
    undefined reference to
    CuTest: C Unit Testing Framework
    screen to tmux: A Humble Quickstart Guide « My Humble Corner
    main,tmain,winmain()等函数——UNICODE sensensen 博客园
    Adding Unit Tests to a C Project NetBeans IDE 6.9 Tutorial
    罗马转数字
    About Luvit
    KISSY Keep It Simple & Stupid, Short & Sweet, Slim & Sexy...
    Create a CSV file
  • 原文地址:https://www.cnblogs.com/deer-cen/p/12210014.html
Copyright © 2011-2022 走看看