Android Studio的笔记--随机数

android java获取随机数

  • String

String

获取 x 位 由0到9组成的随机字符串。
调用方法

Log.i("lxh", "获取由数字0到9组成的随机字符串:" + getStr(12));

函数


    public String RandomStr(int length) {
        String characters = "0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(characters.length());
            char randomChar = characters.charAt(randomIndex);
            sb.append(randomChar);
        }
        return sb.toString();
    }

    private static Set<String> stringSet = new HashSet<>();

    public boolean isRepeat(String str) {
        if (stringSet.size() >= 10000) {
            stringSet.clear();
        }

        if (!stringSet.contains(str)) {
            stringSet.add(str);
            return true;
        }
        return false;
    }

    public String getStr(int length) {
        String back = "";
        while (true) {
            String ss = RandomStr(length);
            Log.d("TAG", "rs=" + ss);
            if (isRepeat(ss)) {
                back = ss;
                break;
            }
        }
        return back;
    }

未完待续…

与君共勉!待续
欢迎指错,一起学习

你可能感兴趣的:(Android,android,studio,笔记,java)