日期:2014-05-20  浏览次数:20864 次

java 循环问题
package com.QQ.pk;

import java.util.*;




public class JavaPackageTest {
private static Random rand = new Random();

public 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) {
String[] results = new String[n];
boolean[] picked = new boolean[flavors.length];

for(int i=0; i<n; i++) {
int t = 0;

do {
t = rand.nextInt(flavors.length);
} while(picked[t]);

results[i] = flavors[t];
picked[t] = true;
}

return results;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i=0; i<20; i++) System.out.println("flavorSet(" + i + ") = ");

String[] f1 = flavorSet(flavors.length);
for(int j=0; j<f1.length; j++) System.out.println("\t" + f1[j]);
}

}


红色部分怎么实现不会重复赋值?不明白?

------解决方案--------------------
boolean[] picked = new boolean[flavors.length];
//picked的元素没有初始化,自动被初始化为false

for(int i=0; i<n; i++) {
int t = 0;

do {
t = rand.nextInt(flavors.length);
} while(picked[t]); 所以第一次for的时候,picked[t]是false,不满足while循环,退出while

results[i] = flavors[t];
picked[t] = true; //接下来给picked[t]赋值为true

//所以第二次for的时候,如果取到的t和第一次的t是一样的,因为picked[t]已经变为true,所以满足while循环继续取t,直到t和第一次t不相同,pitcked[t]才会是false,不满足while,所以这就保证了每次for的时候,取到的t是不重复的,重复的话就会while循环直到不重复为止