Java基础

使用方法

 1 package com.demo5;
 2 
 3 import java.util.Random;
 4 
 5 /*
 6 * 使用步骤:
 7 *       A:导包
 8 *           import java.util.Random;
 9 *       B:创建对象
10 *           Random r = new Random();
11 *       C: 获取随机数
12 *           int num = r.nextInt(10);    // 获取数据的范围:0-9 包括0,不包括10
13 *           int num = r.nextInt(10) +1;    // 获取数据的范围:1-10
14 *           int num = r.nextInt(100) +1;    // 获取数据的范围:1-100
15 *
16 * */
17 
18 public class test1 {
19 
20     public static void main (String[] args) {
21         Random r = new Random();
22         int num = r.nextInt(100);
23         System.out.println("num:" + num);
24     }
25 }

例子

 1 package com.demo5;
 2 
 3 
 4 /*
 5 * 生成一个1-100的随机数,然后通过获取输入的数值进行比对,直到猜对为止
 6 * */
 7 
 8 import java.util.Random;
 9 import java.util.Scanner;
10 
11 public class test1 {
12 
13     public static void main (String[] args) {
14         Random r = new Random();
15 
16         int random_num = r.nextInt(100) + 1;
17 //        System.out.println("num:" + random_num);
18         Scanner sc = new Scanner(System.in);
19 
20         while (true) {
21             System.out.println("请猜一下随机数是多少:");
22             int input_num = sc.nextInt();
23 
24             if (input_num == random_num) {
25                 System.out.println("恭喜猜对了!");
26                 break;
27             } else if (input_num > random_num) {
28                 System.out.println("您输入的值大了");
29             } else {
30                 System.out.println("您输入的值小了");
31             }
32         }
33 
34     }
35 }
原文地址:https://www.cnblogs.com/CongZhang/p/9913121.html