java 返回一个数组(java 编程思想4)P436 例子详解

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]
*///:~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值