求java代码,用数组算法,产生4个随机码,要求不能重复,不要定义数组(ASCII范围字符B-K里选四个)

解决方案 »

  1.   

    啥意思?是B-K随机选4个字母,还是随机生成由B-K的任意4个字母组成字符串?
    不能用数组,能否用集合?
      

  2.   

        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);
        }
    不知道是不是你想要的
      

  3.   

    使用集合:
    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);
      

  4.   

    把需要选取的对象放到集合里,然后每次从集合随机取出一个,并从集合删除,这样下一次取就不会出现重复了
    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()))); /从集合/随机取出后,把它从集合中删除
    }