分析以下需求,并用代码实现 1.产生10个1-20之间的随机数要求随机数不能重复 2.产生10个长度为10的不能重复的字符串(里面只能出现大写字母、小写字母、0-9的数字),并遍历打印输出


import java.util.HashSet;
import java.util.Random;

public class Test03 {
    public static void main(String[] args) {
        //1.产生10个1-20之间的随机数要求随机数不能重复
        HashSet hs = new HashSet<>();
        Random r = new Random();
        while (hs.size() < 10) {
            int i = r.nextInt(20) + 1;
            hs.add(i);
        }
        System.out.println(hs);
        System.out.println("================");
        //2.产生10个长度为10的不能重复的字符串
        // (里面只能出现大写字母、小写字母、0-9的数字),
        // 并遍历打印输出
        HashSet hs1 = new HashSet<>();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 10; i++) {
            sb.append(i);
        }
        for (char i = 'a'; i <= 'z'; i++) {
            sb.append(i);
        }
        for (char i = 'A'; i <= 'Z'; i++) {
            sb.append(i);
        }
        String s = sb.toString();
        System.out.println(s);

        while (hs1.size() < 10) {
           /* String s2 = "";
            while (s2.length() < 10) {
                int i = r.nextInt(s.length());
                String s3 = s.charAt(i) + "";
                s2+=s3;
            }*/
            StringBuilder sb2 = new StringBuilder();
            /*while (sb2.length() < 10) {
                int i = r.nextInt(s.length());
                char c = s.charAt(i);
                sb2.append(c);
            }*/
            for(int i =0 ; i<10;i++){
                int i1 = r.nextInt(s.length());
                char c = s.charAt(i1);
                sb2.append(c);
            }
            String s2 = sb2.toString();
            hs1.add(s2);
        }
        System.out.println(hs1);
    }
}

你可能感兴趣的:(代码案例)