使用 Java 生成用户名(字母数字字符串)

使用 Java 生成“有意义的”用户名(字母数字字符串)的最有效方法是什么?


用户名格式如下:


LastSamurai33

DarkLord96

FallenAngel

IceQueen

LadyPhantom666

DarkSun

感谢您的时间。


万千封印
浏览 206回答 4
4回答

沧海一幻觉

您可以使用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>

扬帆大鱼

加载单独的形容词和名词数组。要生成 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());    }  }}有点乐趣:AncipitalBoxfuls67PlanePerfectionists0TrochaicSerinsUnroundedLightening29ExpectingRemittors37UnscorchedCrackbrains75Conscience-strickenStiles0MuddleheadedBaptistries7GauntLoan11IncompatibleImbalances33StipitateGabbards62AppreciatedAntihistamines41PipyAquanauts83BiosystematicMan-hours92NursedCornhusker15FlocculentCasketsUnshoedZestfulness70SulfuricVoyageur90ParticipialCulpableness27SunrayVidette43UllagedKidneyKhedivalSuperaltars74ArrayedConsorter77MagnetizedWhooper86TrimorphousDiscographers59HolsteredBola89AnagogicalLinacs19UnhumbledFlush99IrritableSuccourerMultispiralMetallurgy2SlitheringBelize8BarkierStimy45Bull-nosedGlossa45UnbiasedProscriptions44BilgierBlackburn7ScarabaeoidIrreality98SolidaryMeningiomas1UnciformSwell5WhateverTe-hees14ConsummatedYou'llBabblingVintnersControlledTergiversations4Rock-bottomConstructers77UltraistLummoxesExpectableMicrohenry65DecentralizedThriller51SaccharicMisanthropes26AnatropousMoldwarp20VelvetyLowlanderMelanousHideawayPromotiveDodecaphonism3AdriaticRebuttersInboundEscallops7RelishableSapotas74UnjaundicedDichromat71BloodshotAbuser63VibrativeKeltic86VeloceBugbear30UnclassifiedSeine-maritimeMetonymicalVenturousness36StemmedHurcheon6RefreshingBaggagesExpressibleOmens74KookiestSegments33AdmonishingNewsdealerSchoolgirlishKeitloas45DisgustfulStrangling9NoduloseGarnishesSeaworthyMurphy30ProximoAcromion13DisciplinalTransposition74UnveiledDissolutions60PrivilegedPorphyrin24PetitCommonage79UnrepugnantBwana33StatelierSordidnessIsorhythmicTulipomania97DeterministicAbstractness85IntercrossedTestudosWolfishOhms4NimbleTelemeter61PerthiticExpertises31WorshipfulHumanness15NiobeanDecumbency57PtolemaicGodspeedDiagonalMultistoreyBrawlingEglantines60SynclasticWalnuts64FibroticMordant28FibrilloseGemels66MitigativeDredger10ConfigurationalOberland67PrerogativeDoits96BoswellianSandman39CantharidalEpanodos23GrippingOracleSoft-coverDeveloping54AdjuratorySilas31MesozoicNorthmanWinterTraveling22

四季花海

组合以下解决方案来生成字母数字字符串,即使用 Java Faker 库生成名称,生成随机整数(解决方案取决于您使用的 java 版本)并组合字符串来构建字母数字字符串。

繁花如伊

试试这个public class UserNameGenerator {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; for (int index = 0; index < 10; index++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Generate: "+ getUserText(null));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; /**&nbsp; &nbsp; * this generates a random username&nbsp; &nbsp; * @param somePseudoName it shall be used in username if provided&nbsp; &nbsp; * @return&nbsp; &nbsp; */&nbsp; &nbsp; private static String getUserText(String somePseudoName) {&nbsp; &nbsp; &nbsp; &nbsp; String[] nameArray = new String[]{"hello", "world", "someday", "mltr", "coldplay"};&nbsp; &nbsp; &nbsp; &nbsp; String userName = "";&nbsp; &nbsp; &nbsp; &nbsp; if (somePseudoName != null && somePseudoName.length() > 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; userName = somePseudoName;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; userName = nameArray[new Random().nextInt(nameArray.length)];&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return userName + getRandomNumber();&nbsp; &nbsp; }&nbsp; &nbsp; /**&nbsp; &nbsp; * this shall create a random number&nbsp; &nbsp; * @return a number text&nbsp; &nbsp; */&nbsp; &nbsp; private static String getRandomNumber() {&nbsp; &nbsp; &nbsp; &nbsp; StringBuilder numberText = new StringBuilder();&nbsp; &nbsp; &nbsp; &nbsp; int[] numbersArray = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};&nbsp; &nbsp; &nbsp; &nbsp; int totalNumbers = new Random().nextInt(3);&nbsp; &nbsp; &nbsp; &nbsp; for (int index = 0; index < totalNumbers; index++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; numberText.append(numbersArray[new Random().nextInt(numbersArray.length)]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return numberText.toString();&nbsp; &nbsp; }}输出Generate: hello8Generate: mltrGenerate: someday4Generate: coldplay22Generate: worldGenerate: worldGenerate: coldplay79Generate: worldGenerate: coldplayGenerate: coldplay15
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java