suchen

Heim  >  Fragen und Antworten  >  Hauptteil

java - 随机不重复昵称怎么生成?

随机不重复昵称怎么生成?

阿神阿神2770 Tage vor951

Antworte allen(5)Ich werde antworten

  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:48:14

    1. HashSet 判断是否重复

    2. UUID 保证不重复

    Antwort
    0
  • 天蓬老师

    天蓬老师2017-04-17 17:48:14

    可以随机中文再加随机英文字符串再加随机数字。再重复的话,后边数字顺序递增。

    Antwort
    0
  • PHP中文网

    PHP中文网2017-04-17 17:48:14

    package test;

    import java.io.UnsupportedEncodingException;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Random;
    public class RandomChinese {

    public static void main(String args[]) {
        HashSet<String> set = new HashSet<String>();
        for (int i = 0; i < 100; i++) {
            String chineseName = getRandomJianHan(3);
            if (!set.contains(chineseName)) {
                set.add(chineseName);
            }
        }
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()) {
            System.err.print(iterator.next() + "\n");
        }
    }
    public static String getRandomJianHan(int len) {
        String ret = "";
        for (int i = 0; i < len; i++) {
            String str = null;
            int hightPos, lowPos; // 定义高低位
            Random random = new Random();
            hightPos = (176 + Math.abs(random.nextInt(39))); // 获取高位值
            lowPos = (161 + Math.abs(random.nextInt(93))); // 获取低位值
            byte[] b = new byte[2];
            b[0] = (new Integer(hightPos).byteValue());
            b[1] = (new Integer(lowPos).byteValue());
            try {
                str = new String(b, "GBK"); // 转成中文
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
            ret += str;
        }
        return ret;
    }

    }

    Antwort
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:48:14

    /**
         * 生成交易号
         */
        public function generatePaymentId()
        {
            $i = rand(0, 9999);
            do {
                if (9999 == $i) {
                    $i = 0;
                }
                $i++;
                $id = time() . str_pad($i, 4, '0', STR_PAD_LEFT);
                $row = (new Query())->from(self::tableName())->where(['id' => $id])->exists();
            } while ($row);
            return $id;
        }

    楼上的代码我就不评价了

    Antwort
    0
  • PHP中文网

    PHP中文网2017-04-17 17:48:14

    方案一,找个地方,抓个昵称库
    方案二,找个中文词库,人工大至过下,两个词之间随机组合

    Antwort
    0
  • StornierenAntwort