1 //20160518 Math類常用方法 練習
2 package MyPackage;
3
4 public class MathDemo {//定義主類和main方法
5
6 public static void main(String[] args) {
7 System.out.println(Math.sqrt(16));// Math類常用方法:求平方根
8 System.out.println(Math.pow(2, 3));// Math類常用方法:多少的多少次方
9 System.out.println(Math.round(13.64));// Math類常用方法:四捨五入
10 System.out.println(Math.random());// Math類常用方法:產生一個隨機數
11 }
12
13 }
Math類中的方法都是靜態方法,直接使用“類.方法名稱()”的形式調用即可。
---------------------------------------------------------------------------------------------
1 //20150518 Random類:隨機產生數值 練習
2 package MyPackage; //自己定義的包
3
4 import java.util.Random; //導入需要的Random包
5
6 public class RandomDemo { // 定義主類
7 public static void main(String[] args) { // mian方法
8 Random r = new Random(); // 實例化Random類的對象r
9 for (int i = 0; i < 6; i++) { // 循環6次輸入6個隨機數
10 System.out.print(r.nextInt(100) + "\t"); // 產生隨機數並指定產生的數值范圍小於100
11 }
12 }
13
14 }
Random類隨機產生數值,並可以指定產生數值的范圍大小。