#用到了一个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;
}
}