*問題情境:*小明、小芳在星期五放學後一起回家,三人花了10元買了20顆糖。三人當即一人吃了一顆,剩下17顆。他們想通過抓鬮6,6,5的方式分配剩下的糖,請編寫java 程序模擬此過程。
package com.test;
public class TestTask {
public static void main(String[] args) {
int candy[] = doRand(0,4,3);
int test[] = { 6,6,5};
System.out.println("剩餘的糖果數:");
for(int i = 0;i<test.length;i++){
System.out.print(test[i]+" ");
}
System.out.println("\n三個隨機數字:");
for(int i = 0;i<candy.length;i++){
System.out.print(candy[i]+" ");
}
System.out.println("\nrun result:");
for(int i = 0;i<test.length;i++){
int count = candy[i] ;
System.out.print("第"+(i+1)+"次取出的糖果數是:"+test[count-1]+"顆!");
System.out.println();
}
}
public static int[] doRand(int min, int max, int n){ //doRand隨機數產生方法.
if (n >= (max - min + 1) || max < min) {
String str ="參數設置錯誤";
System.out.println(str);
}
int[] result = new int[n];
int count = 0;
while(count < n) {
int num = (int) (Math.random() * (max - min)) + min;//調用random工具類,產生指定範圍的隨機數.
boolean flag = true;
for (int j = 0; j < n; j++) {
if(num == result[j]){
flag = false;
break;
}
}
if(flag){
result[count] = num;
count++;
}
}
return result;
}
}
結果展示:
核心代碼:doRand指定隨機範圍生成數組
public static int[] doRand(int min, int max, int n){ //doRand隨機數產生方法.
if (n >= (max - min + 1) || max < min) {
String str ="參數設置錯誤";
System.out.println(str);
}
int[] result = new int[n];
int count = 0;
while(count < n) {
int num = (int) (Math.random() * (max - min)) + min;//調用random工具類,產生指定範圍的隨機數.
boolean flag = true;
for (int j = 0; j < n; j++) {
if(num == result[j]){
flag = false;
break;
}
}
if(flag){
result[count] = num;
count++;
}
}
return result;
}
嘿嘿,分享完畢!下次再約咯!