public static void main(String[] args) { int count = 1; Set<Character> set = new HashSet<>(4); while (count < 5) { // ASCII B对应的十进制值 int Min = 66; // ASCII K对应的十进制值 int Max = 75; // B-K范围内,包含B/K值 int result = Min + (int)(Math.random() * ((Max - Min) + 1)); if (set.add((char)result)) { count ++; } } System.out.println(set); } 不知道是不是你想要的
使用集合: Random random = new Random(); Set<Character> set = new HashSet<>(4); while (true) { char result = (char) ('B' + random.nextInt('K' - 'B')); if(set.add(result)&&set.size()==4){ break; } } System.out.println(set);
把需要选取的对象放到集合里,然后每次从集合随机取出一个,并从集合删除,这样下一次取就不会出现重复了 for example Random ran = new Random(); List<Character> list = new ArrayList<>(Arrays.asList(new Character[] {'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'})); for (int i=0; i<4; i++) { System.out.println(list.remove(ran.nextInt(list.size()))); /从集合/随机取出后,把它从集合中删除 }
不能用数组,能否用集合?
int count = 1;
Set<Character> set = new HashSet<>(4);
while (count < 5) {
// ASCII B对应的十进制值
int Min = 66;
// ASCII K对应的十进制值
int Max = 75;
// B-K范围内,包含B/K值
int result = Min + (int)(Math.random() * ((Max - Min) + 1));
if (set.add((char)result)) {
count ++;
}
}
System.out.println(set);
}
不知道是不是你想要的
Random random = new Random();
Set<Character> set = new HashSet<>(4);
while (true) {
char result = (char) ('B' + random.nextInt('K' - 'B'));
if(set.add(result)&&set.size()==4){
break;
}
}
System.out.println(set);
for example
Random ran = new Random();
List<Character> list = new ArrayList<>(Arrays.asList(new Character[] {'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'}));
for (int i=0; i<4; i++) {
System.out.println(list.remove(ran.nextInt(list.size()))); /从集合/随机取出后,把它从集合中删除
}