1. 程式人生 > >JAVA學習日誌 一個關於隨機骰子1-1000計數的程式

JAVA學習日誌 一個關於隨機骰子1-1000計數的程式

這個題目主要是為了測試switch語句。另外測試了隨機函式random的隨機情況。很簡單,不多做介紹

public class TestRandom{
public static void main(String[] args){
int t,d_1=0,d_2=0,d_3=0,d_4=0,d_5=0,d_6=0;
for (int i=1;i<=1000;i++){
t=(int)(1+Math.random()*6);  //隨機生成一個0到1的小數,乘6加1取整數1-6.
switch (t){
case 1:
d_1++;
break;
case 2:
d_2++;
break;
case 3:
d_3++;
break;
case 4:
d_4++;
break;
case 5:
d_5++;
break;
case 6:
d_6++;
break;
}

}
System.out.println("測試1000個隨機篩子數的出現次數:");
System.out.print("其中1個數:");
System.out.println(d_1);
System.out.print("其中2個數:");
System.out.println(d_2);
System.out.print("其中3個數:");
System.out.println(d_3);
System.out.print("其中4個數:");
System.out.println(d_4);
System.out.print("其中5個數:");
System.out.println(d_5);
System.out.print("其中6個數:");
System.out.println(d_6);
}
}