package arrays;
//: arrays/IceCream.java
// Returning arrays from methods.
import java.util.*;
public class IceCream {
private static Random rand = new Random(47);
static final String[] FLAVORS = {
"Chocolate", "Strawberry", "Vanilla Fudge Swirl",
"Mint Chip", "Mocha Almond Fudge", "Rum Raisin",
"Praline Cream", "Mud Pie"
};
public static String[] flavorSet(int n) {
if(n > FLAVORS.length)
throw new IllegalArgumentException("Set too big");
String[] results = new String[n];
//System.out.println(FLAVORS.length); FLAVORS.length=8
boolean[] picked = new boolean[FLAVORS.length];//定义一个 boolean 类型的数组 大小是FLAVORS.length=8
for(int i = 0; i < n; i++) {
int t;
do
{ t = rand.nextInt(FLAVORS.length); //产生随机数
System.out.println(picked[t]);}
while(picked[t]);
/*boolean 数组中默认初始化为 false while 遇到“假” 循环结束
并且 results[i] = FLAVORS[t] */
// System.out.println(i+" "+t);
results[i] = FLAVORS[t];
picked[t] = true;// 确保不会重复
}
return results;
}
public static void main(String[] args) {
for(int i = 0; i < 7; i++)
System.out.println(Arrays.toString(flavorSet(3)));
System.out.println(new boolean[FLAVORS.length]);
}
} /* Output:
[Rum Raisin, Mint Chip, Mocha Almond Fudge]
[Chocolate, Strawberry, Mocha Almond Fudge]
[Strawberry, Mint Chip, Mocha Almond Fudge]
[Rum Raisin, Vanilla Fudge Swirl, Mud Pie]
[Vanilla Fudge Swirl, Chocolate, Mocha Almond Fudge]
[Praline Cream, Strawberry, Mocha Almond Fudge]
[Mocha Almond Fudge, Strawberry, Mint Chip]
*///:~
java 返回一个数组(java 编程思想4)P436 例子详解
最新推荐文章于 2021-02-25 07:59:09 发布