手记

Java入门第三季第六章排序练习

借鉴慕友提供的随机产生字符串的方法,自己整理所得;

    public void sort2(){
        List<String> strSort = new ArrayList<>();
        String c = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";        
        Random random = new Random();
        StringBuffer temp = new StringBuffer();  //用于临时存储产生的10位随机字符串
        String  s = new String();
        int i =0;
          do {
          for (int j = 0; j < 10; j++) {
            char ch = c.charAt(random.nextInt(c.length()));
            temp.append(Character.toString(ch));
          }
              s  = temp.toString();
              temp.setLength(0);  //清空当前的StringBuffer
              strSort.add(s);
              i++;
           } while (strSort.contains(s)&&i<=10);
        System.out.println("----------排序前----------------");
        for (String s1 : strSort) {
               System.out.println("添加到序列中的字符串" + s1);
        }
        Collections.sort(strSort);
        System.out.println("----------排序后----------------");
        for (String s1 : strSort) {
               System.out.println("添加到序列中的字符串" + s1);
        }
    }
0人推荐
随时随地看视频
慕课网APP