public class IceCream { private static Random random = new Random(47); private static final String[] FLAVORS = new String[]{"A","B","C","D","E","F","G","H","I","J","K"}; public static String[] flavorSet(int n){ if(n>FLAVORS.length) throw new IllegalArgumentException("Set too big"); String[] result = new String[n]; boolean[] picked = new boolean[FLAVORS.length];//判断是否重复 for (int i = 0; i < n; i++) { int t ; do { t = random.nextInt(FLAVORS.length); } while (picked[t]);//false:不重复的 true:重复的,会再次的循环 result[i] = FLAVORS[t]; picked[t] = true; } return result; } public static void main(String[] args) { System.out.println(Arrays.toString(flavorSet(3))); } }
do...While用法
猜你喜欢
转载自mvplee.iteye.com/blog/2209544
今日推荐
周排行