1. 程式人生 > >java隨機數 Math.random 和Random類

java隨機數 Math.random 和Random類

java實現隨機數有兩種方式1)Math.random()和Random類方法,我簡單記錄一下,方便自己回顧,更希望幫助他人。

Math.random()

這個方法是Math類提供的方法,用來返回一個處於0-1之間的浮點數。

用處:

1.返回一個位於0--1隨機浮點數,對浮點數進行處理

System.out.println(String.format("%.2f", Math.random())); //0.46 

對小數尾數進行格式化,使其小數點後兩位.

2.返回一個位於0--N之間的整數:

int number = (int)(Math.random()*n)

例如 返回一個位於0---18之間的整數:

int number = (int)(Math.random()*18)

3.返回一個位於n--m之間的整數

int number = (int)(n+Math.random()*(m-n));

例如:返回一個位於20--25之間的整數:

int number = (int)(20+Math.random()*5);
		System.out.println(number);

4.返回位於字母’n‘---’m‘之間的任意字元

例如:返回字母'a'--'z' 之間的任意字母;

char ch = (char)('a'+Math.randon()*('z'-'a')+1)

例項小遊戲(猜數字)

public class NumberRiddle {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		while (true) {
			System.out.println("是否開始遊戲,按0表示退出,按任意鍵繼續(輸入負數自動退出遊戲)");
			int inputNumber = scan.nextInt();
			if (inputNumber != 0) {
				int imageNumner = (int) (Math.random() * 100);
				System.out.println("隨機數已產生,位於1-100之間,請開始猜數");
				while (inputNumber != imageNumner) {
					inputNumber = scan.nextInt();
					if (inputNumber < imageNumner) {
						System.out.println("輸入數字太小,請重新猜");
					} else if (inputNumber > imageNumner) {
						System.out.println("請入數字太大,請重新猜");
					} else if (inputNumber < 0) {
						return;
					}
				}
				System.out.println("恭喜你,猜對啦!");

			} else {
				System.out.println("謝謝參與");
				return;
			}
		}
	}
}

Random類:

例項方式1)Random random1 = new Random();

2)Random random2 = new Random(seedValue);

seedValue;隨機數種子,傳入一個數字,系統會根據隨機數種子來生成隨機數(主要是為了方便可再現隨機數生成),預設1以系統當前時間作為隨機數種子;

常用方法(Random.xx):

  1. nextInt()       返回值型別int       返回一個隨機整數;
  2. nextInt(int n)   返回一個等於0小於n的隨機整數;
  3. nextLong      返回一個隨機長整形值;
  4. nextboolean 返回一個隨機布林型別 
  5. 以此類推;

實戰小專案(模擬微信紅包功能)

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

public class ReaPaper {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		System.out.println("請輸入你要派發紅包的金額");
		double total = scan.nextFloat();
		System.out.println("請輸入你要派發紅包的份數");
		int portion = scan.nextInt();

		double min = 0.01; // 紅包最小金額
		Random random = new Random();
		System.out.println("開始隨機產生紅包");
		for (int i = 1; i <= portion; i++) {
			// 本次紅包可能最大值 max = 可用金額-(紅包總數-已經發送紅包的數目)*最小紅包金額;
			double max = total - (portion - i) * 0.01;
			double bound = max - min; // 本次紅包可取值範圍

			double money = random.nextInt((int) bound * 100) / 100;
//random.nextInt(round) 可以在該round隨機產生一個隨機數  由於引數是整數,所以我們簡單修改
//			double money = String.format("%.2f", Math.random()args)*bound;
			money += 0.01; // 防止出現0元
			System.out.println("第" + i + "份紅包的金額是--->" + money);
			total = total - money;
		}
	}
}