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>
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
TA贡献1811条经验 获得超5个赞
组合以下解决方案来生成字母数字字符串,即使用 Java Faker 库生成名称,生成随机整数(解决方案取决于您使用的 java 版本)并组合字符串来构建字母数字字符串。
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
添加回答
举报