`

返回数组

 
阅读更多

1.返回一个数组

package sj.ThinkInJava.Chapter16.Section03.example;

import java.util.Arrays;
import java.util.Random;

/**
 * 返回String数组
 * 
 * @author Timmy
 * @time 2014-07-18
 * 
 */
public class Ice_Cream {

	public static void main(String[] args) {
		for (int i = 0; i < 7; i++)
			System.out.println(Arrays.toString(flavor_Set(3)));
	}

	// 创建随机数对象rand
	private static Random rand = new Random(47);

	// 聚集初始化数组FLAVORS
	static final String[] FLAVORS = { "Chocolate", "Strawberry",
			"Vanilla Fudge Swirl", "Mint Chip", "Mocha Almond Fudge",
			"Rum Raisin", "Praline Cresm", "Mud Pie" };

	/**
	 * 创建容量为n的String型数组results
	 * 
	 * @param n
	 *            =>参数决定数组的容量
	 * @return=>返回一个数组
	 */
	public static String[] flavor_Set(int n) {
		// 超过数组长度,抛出异常
		if (n > FLAVORS.length)
			throw new IllegalArgumentException("数组越界!");

		// 创建数组对象results
		String[] results = new String[n];
		boolean[] picked = new boolean[FLAVORS.length];

		for (int i = 0; i < n; i++) {
			int t;
			do
				t = rand.nextInt(FLAVORS.length);
			while (picked[t]);
			results[i] = FLAVORS[t];
			picked[t] = true;
		}
		return results;
	}
} /*
   * [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 Cresm, Strawberry, Mocha Almond Fudge]
   * [Mocha Almond Fudge, Strawberry, Mint Chip]
   */

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics