面向對象-------Math類(十七)

 A:Math類概述
    * 類包含用於執行基本數學運算的方法
B:Math類特點
    * 由於Math類在java.lang包下,所以不需要導包。
    * 因爲它的成員全部是靜態的,所以私有了構造方法
C:獲取隨機數的方法
    * public static double random():返回帶正號的 double 值,該值大於等於 0.0 且小於 1.0。
D:我要獲取一個1-100之間的隨機數
    * int number = (int)(Math.random()*100)+1;

class Demo2_Math {
	public static void main(String[] args) {
		//double d = Math.random();
		//System.out.println(d);
		
		//Math.random()會生成大於等於0.0並且小於1.0的僞隨機數
		for (int i = 0;i < 10 ;i++ ) {
			System.out.println(Math.random());
		}

		//生成1-100的隨機數
		//Math.random()0.0000000 - 0.999999999
		//Math.random() * 100 ====> 0.00000 - 99.999999999
		//(int)(Math.random() * 100) ====> 0 - 99
		//(int)(Math.random() * 100) + 1

		for (int i = 0;i < 10 ;i++ ) {
			System.out.println((int)(Math.random() * 100) + 1);
		}
	}
}

import java.util.Scanner;
class Test1_GuessNum {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);		//創建鍵盤錄入對象
		System.out.println("請輸入一個整數,範圍在1-100之間");
		int guessNum = (int)(Math.random() * 100) + 1;	//心裏想的隨機數
		while (true) {			//因爲需要猜很多次,所以用無限循環
			int result = sc.nextInt();	//大家猜的數
                    /*
                    如果你們猜的數大於了我心裏想的數.提示大了;
                    如果你們猜的數小於了我心裏想的數,提示小了;
                    否則,中了.
                      */
			if (result > guessNum) {					
		         System.out.println("大了");					
			} else if (result < guessNum) {					
				System.out.println("小了");				
			} else {							
				System.out.println("中了");				
				break;
			}
		}
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章