为了账号安全,请及时绑定邮箱和手机立即绑定

生成随机字符串,欢迎指教

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package com.imooc;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
 
public class CollectionSort {
    ArrayList<String> RandomList = new ArrayList<String>();
/**
 * 向ArrayList中添加字符串
 */
    public void addList() {
        String str;
        for (int i = 0; i < 10; i++) {
            do {
                str = getString();
            while (RandomList.contains(str));
            RandomList.add(str);
            System.out.println("成功添加:"+str);
        }
    }
/**
 * 排序
 */
    public void sortCollection() {
            System.out.println("--------排序前--------");
            for (String string : RandomList) {
                System.out.println("随机数列:"+string);
            }
            System.out.println("--------排序后--------");
            Collections.sort(RandomList);
            for (String string : RandomList) {
                System.out.println("随机数列:"+string);
            }
    }
/**
 * 生成长度10以内的随机字符串
 * @return
 */
    public String getString() {
        Random random = new Random();
        String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST";
        StringBuilder sb = new StringBuilder();
        int length = str.length();
        do {
            int ran = random.nextInt(length);
            sb.append(str.charAt(ran));
        while (sb.length() < random.nextInt(10));
        return sb.toString();
 
    }
    //生成3个1000以内的不重复的数字
    public void third(){
        int i = 1;
        Random random = new Random();
        int[] id =new int[3];
        id[0]=random.nextInt(1000);
        while(i<3){
            if(id[i] != random.nextInt(1000)){
                id[i] = random.nextInt(1000);
            }else{
                continue;
            
                i++;
        }
        for (int j : id) {
            System.out.println(j);
        }
    }
     
 
    public static void main(String[] args) {
            CollectionSort cs = new CollectionSort();
            cs.addList();
            cs.sortCollection();
//          cs.third();
    }
 
}


正在回答

代码语言

1 回答

楼主,你的third()方法好像有点问题...你把代码中的“1000”改为“10”,运行会出现重复数字!

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

生成随机字符串,欢迎指教

我要回答 关注问题
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号