#用到了一個Random的類。
import java.util.Random;
public class GetIceCream {
public static void main(String[] args) {
String[] iceCream = new String[] { "香蕉", "草莓", "香芋", "巧克力", "奶油", "咖啡" };//可以換成不同數量的口味
String[] getIceCream = getIce(iceCream);
System.out.println();
System.out.print("隨機四種口味: ");
for (int i = 0; i < getIceCream.length; i++) {
System.out.print(getIceCream[i] + " ");
}
}
public static String[] getIce(String[] iceCream) {
String[] getIceCream = new String[4];
boolean[] autoGet = new boolean[6];// 創建使用狀態
Random rand = new Random();// 隨機取下標
for (int num = 0; num < getIceCream.length; num++) {
int a = rand.nextInt(autoGet.length);
if (!autoGet[a]) {//判斷是否爲false,如果爲true,則退回上一個,再循環
getIceCream[num] = iceCream[a];
// System.out.print(a+" ");
autoGet[a] = true;// 選中的改爲true
} else { //銜接上方
num--;
}
}
// 獲取什麼口味沒被選中
for (
int i = 0; i < autoGet.length; i++) {
System.out.print(iceCream[i] + " ");
System.out.print(autoGet[i] + " ");
}
return getIceCream;
}
}