亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Java 生成用戶名(字母數字字符串)

使用 Java 生成用戶名(字母數字字符串)

萬千封印 2023-07-28 16:41:30
使用 Java 生成“有意義的”用戶名(字母數字字符串)的最有效方法是什么?用戶名格式如下:LastSamurai33DarkLord96FallenAngelIceQueenLadyPhantom666DarkSun感謝您的時間。
查看完整描述

4 回答

?
滄海一幻覺

TA貢獻1824條經驗 獲得超5個贊

您可以使用Java Faker生成各種隨機假數據。

這是一個例子

public static void main(String[] args) {

? ? ? ? Faker faker = new Faker();

? ? ? ? System.out.println(faker.superhero().prefix()+faker.name().firstName()+faker.address().buildingNumber());

? ? ? ? //MrSharon55747

? ? ? ? //IllustriousDock6698

? ? ? ? //CyborgDelilah207

? ? ? ? //GeneralAllison01931

? ? ? ? //RedWillard4366

? ? ? ? //TheJarvis71802

? ? }

Maven 依賴:


<dependency>

? ? <groupId>com.github.javafaker</groupId>

? ? <artifactId>javafaker</artifactId>

? ? <version>1.0.1</version>

</dependency>


查看完整回答
反對 回復 2023-07-28
?
揚帆大魚

TA貢獻1799條經驗 獲得超9個贊

加載單獨的形容詞和名詞數組。要生成 uid,請隨機選擇其中一個。大寫。決定是否要附加一個整數以及應該附加一個隨機數。連接并返回。

import java.io.IOException;

import java.nio.file.Files;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.util.ArrayList;

import java.util.List;

import java.util.Random;

import java.util.stream.Stream;


public class UserIdGenerator {

? final List<String> adjectives = new ArrayList();

? final List<String> nouns = new ArrayList();

? final int minInt;

? final int maxInt;

? final Random random;


? public UserIdGenerator(Path adjectivesPath, Path nounsPath, int minInt, int maxInt)

? ? ? throws IOException {

? ? this.minInt = minInt;

? ? this.maxInt = maxInt;

? ? try (Stream<String> lines = Files.lines(adjectivesPath)) {

? ? ? lines.forEach(line -> adjectives.add(capitalize(line)));

? ? }

? ? try (Stream<String> lines = Files.lines(nounsPath)) {

? ? ? lines.forEach(line -> nouns.add(capitalize(line)));

? ? }

? ? this.random = new Random();

? }


? private static String capitalize(String s) {

? ? return Character.toUpperCase(s.charAt(0)) + s.substring(1).toLowerCase();

? }


? public String generate() {

? ? StringBuilder sb = new StringBuilder()

? ? ? ? .append(adjectives.get(random.nextInt(adjectives.size())))

? ? ? ? .append(nouns.get(random.nextInt(nouns.size())));

? ? int i = random.nextInt(maxInt);

? ? if (i >= minInt) {

? ? ? sb.append(i - minInt);

? ? }

? ? return sb.toString();

? }


? public static void main(String [] args) throws IOException {

? ? UserIdGenerator userIdGenerator = new UserIdGenerator(

? ? ? ? Paths.get("28K adjectives.txt"),?

? ? ? ? Paths.get("91K nouns.txt"),?

? ? ? ? 20, 120);

? ? for (int i = 0; i < 100; ++i) {

? ? ? System.out.println(userIdGenerator.generate());

? ? }

? }

}

有點樂趣:


AncipitalBoxfuls67

PlanePerfectionists0

TrochaicSerins

UnroundedLightening29

ExpectingRemittors37

UnscorchedCrackbrains75

Conscience-strickenStiles0

MuddleheadedBaptistries7

GauntLoan11

IncompatibleImbalances33

StipitateGabbards62

AppreciatedAntihistamines41

PipyAquanauts83

BiosystematicMan-hours92

NursedCornhusker15

FlocculentCaskets

UnshoedZestfulness70

SulfuricVoyageur90

ParticipialCulpableness27

SunrayVidette43

UllagedKidney

KhedivalSuperaltars74

ArrayedConsorter77

MagnetizedWhooper86

TrimorphousDiscographers59

HolsteredBola89

AnagogicalLinacs19

UnhumbledFlush99

IrritableSuccourer

MultispiralMetallurgy2

SlitheringBelize8

BarkierStimy45

Bull-nosedGlossa45

UnbiasedProscriptions44

BilgierBlackburn7

ScarabaeoidIrreality98

SolidaryMeningiomas1

UnciformSwell5

WhateverTe-hees14

ConsummatedYou'll

BabblingVintners

ControlledTergiversations4

Rock-bottomConstructers77

UltraistLummoxes

ExpectableMicrohenry65

DecentralizedThriller51

SaccharicMisanthropes26

AnatropousMoldwarp20

VelvetyLowlander

MelanousHideaway

PromotiveDodecaphonism3

AdriaticRebutters

InboundEscallops7

RelishableSapotas74

UnjaundicedDichromat71

BloodshotAbuser63

VibrativeKeltic86

VeloceBugbear30

UnclassifiedSeine-maritime

MetonymicalVenturousness36

StemmedHurcheon6

RefreshingBaggages

ExpressibleOmens74

KookiestSegments33

AdmonishingNewsdealer

SchoolgirlishKeitloas45

DisgustfulStrangling9

NoduloseGarnishes

SeaworthyMurphy30

ProximoAcromion13

DisciplinalTransposition74

UnveiledDissolutions60

PrivilegedPorphyrin24

PetitCommonage79

UnrepugnantBwana33

StatelierSordidness

IsorhythmicTulipomania97

DeterministicAbstractness85

IntercrossedTestudos

WolfishOhms4

NimbleTelemeter61

PerthiticExpertises31

WorshipfulHumanness15

NiobeanDecumbency57

PtolemaicGodspeed

DiagonalMultistorey

BrawlingEglantines60

SynclasticWalnuts64

FibroticMordant28

FibrilloseGemels66

MitigativeDredger10

ConfigurationalOberland67

PrerogativeDoits96

BoswellianSandman39

CantharidalEpanodos23

GrippingOracle

Soft-coverDeveloping54

AdjuratorySilas31

MesozoicNorthman

WinterTraveling22



查看完整回答
反對 回復 2023-07-28
?
四季花海

TA貢獻1811條經驗 獲得超5個贊

組合以下解決方案來生成字母數字字符串,即使用 Java Faker 庫生成名稱,生成隨機整數(解決方案取決于您使用的 java 版本)并組合字符串來構建字母數字字符串。

查看完整回答
反對 回復 2023-07-28
?
繁花如伊

TA貢獻2012條經驗 獲得超12個贊

試試這個


public class UserNameGenerator {


    public static void main(String[] args) {


        for (int index = 0; index < 10; index++) {

            System.out.println("Generate: "+ getUserText(null));

        }

    }


    /**

    * this generates a random username

    * @param somePseudoName it shall be used in username if provided

    * @return

    */

    private static String getUserText(String somePseudoName) {

        String[] nameArray = new String[]{"hello", "world", "someday", "mltr", "coldplay"};

        String userName = "";

        if (somePseudoName != null && somePseudoName.length() > 0) {

            userName = somePseudoName;

        } else {

            userName = nameArray[new Random().nextInt(nameArray.length)];

        }

        return userName + getRandomNumber();

    }


    /**

    * this shall create a random number

    * @return a number text

    */

    private static String getRandomNumber() {

        StringBuilder numberText = new StringBuilder();

        int[] numbersArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};


        int totalNumbers = new Random().nextInt(3);


        for (int index = 0; index < totalNumbers; index++) {

            numberText.append(numbersArray[new Random().nextInt(numbersArray.length)]);

        }

        return numberText.toString();

    }

}

輸出


Generate: hello8

Generate: mltr

Generate: someday4

Generate: coldplay22

Generate: world

Generate: world

Generate: coldplay79

Generate: world

Generate: coldplay

Generate: coldplay15


查看完整回答
反對 回復 2023-07-28
  • 4 回答
  • 0 關注
  • 281 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號