gpt4 book ai didi

java - 用Java制作一个名称生成器,将生成的字符数量限制为12个,但不会截断单词?

转载 作者:太空宇宙 更新时间:2023-11-04 06:12:48 24 4
gpt4 key购买 nike

我正在寻找一种制作随机名称生成器的方法,这会将生成的字符串的字符数限制为 12 个。

例如,我有一个字符串“Dragon”和另一个字符串“killer13”。如果随机匹配,则有 14 个字符。我希望它选择适合 2 个完整字符串的名称,总长度不超过 12 个字符;所以如果“Dragon”和“killer13”匹配在一起,我不想得到“Dragonkiller”,因为它切断了“killer13”的最后两个字符。

最佳答案

做这样的事情怎么样?

// A List to hold all the names
List<String> namesList = new ArrayList<>();

// Create the full list of names
String[] names = {"mike", "Dragon", "jason", "freddy", "john", "mic"};

// Store them into the List
namesList = new ArrayList(Arrays.asList(names));

// Randomly get the first part of the name
int randomIndex = new Random().nextInt(names.length - 1);
String firstName = namesList.get(randomIndex);
String lastName = null;

// Figure out the size remaining
int remainSize = 12 - firstName.length();

// If desired, remove the element from the List so you don't get "DragonDragon"
namesList.remove(randomIndex);

// Randomly shuffle the list
long seed = System.nanoTime();
Collections.shuffle(namesList, new Random(seed));

// For each name, grab the first one that will complete the size 12
for (String name : namesList) {
int nameSize = name.length();

if (nameSize <= remainSize) {
lastName = name;
break;
}
}

String newName = firstName + lastName;
System.out.println("Generated name: " + newName + ", with size " + newName.length());

关于java - 用Java制作一个名称生成器,将生成的字符数量限制为12个,但不会截断单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28504816/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com