java Random class (API)

First, the process

1, the leader packet

2, instantiation

3, using (a member of class methods)

Second, the role

Generates a random number in random similar to python

Third, the common method

1, nextInt (), generates a random number range of data type int

2, nextInt (int: bound), starting from 0, the left and right to open and close (care regardless of tail)

example

Requirements: The value of n is inputted, a random number calculated in 1 ~ n can take the n

package cn.wt.day07.Demon02A;

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

public class Demon02Rand {
    public static void main(String[] args) {
        System.out.print("请输入取值范围:");
        Scanner scan = new Scanner(System.in);
        int num = scan.nextInt();
        Random ran = new Random();
        for (int i = 0; i < 20; i++) {
            int randNum = ran.nextInt(num) + 1;
            System.out.println(randNum);
        }
    }
}

Requirements: Guess Price 1-100 up to five times greater than less than prompt tips

Package cn.wt.day07.Demon02A; 


Import java.util.Random;
 Import java.util.Scanner; 

public  class Demon03Rand {
     public  static  void main (String [] args) {
         // 1. generates a random number 
        the Random RAND = new new the Random ();
         int randnum rand.nextInt = (100) +. 1 ; 
        Scanner Scan = new new Scanner (the System.in);
         int COUNT = 0 ;
         the while (COUNT <. 5 ) { 
            of System.out.print ( "Please enter the number of sub" );
             int guessNum = scan.nextInt();
            if (guessNum > randNum){
                System.out.println("大了");
            } else if (guessNum < randNum){
                System.out.println("小了");
            } else {
                System.out.println("答对了");
                break;
            }
            count ++;
        }

    }
}

Guess you like

Origin www.cnblogs.com/wt7018/p/12189736.html