gpt4 book ai didi

java - 是否可以在Java中生成自定义字符

转载 作者:行者123 更新时间:2023-12-02 02:09:26 25 4
gpt4 key购买 nike

我对编程很陌生,我想做一个简单的任务是否可以从特定列表生成 Java 中的自定义字符?

例如,我希望程序仅从该字符 A H F G D 中为我提供随机字符?

可能吗?

最佳答案

有一种简单的方法可以实现从给定的字符集中获取伪随机元素。您可以使用 Random.nextInt() (来自 java.util 包)来实现此目的。

您可以考虑创建一个 char 数组,然后让该方法为您选择一个元素。

这是使用 Random 类的示例:

char[] array = new char[] {'A', 'H', 'F', 'G', 'D', };
Random rand = new Random();
char chosenOne = array[rand.nextInt(array.length)]; // there is a pseudorandomly chosen index for array in range of 0 inclusive to 5 exclusive
<小时/>

编辑:根据您的评论(您说您想从不同长度的字符串集中随机选择元素(这样它们就不再是char了) (因为 char单个字符 - '1' 或 '0',而不是 ' 10'),那么它们就是 String),我能想到的实现该结果的最轻松的方法是在字符串中的这些值之间放置一个分隔符。这是一个可能的实现(我在代码注释中做了一些额外的解释):

public static void main(String[] args) {
String[] array = splitToSeparateElements("A,H,F,10,G,D,1,0,2000"); // store the result of calling splitToElements() with a
// given String as argument
Random rand = new Random();
for (int i = 0; i < 10; i++) { // this loop is just to print more results to console
System.out.print(array[rand.nextInt(array.length)] + " "); // print pseudorandom element of array to the console
}
}

public static String[] splitToSeparateElements(String inputString) {
String[] splitted = inputString.split(","); // split String to separate Strings in the place of delimiter passed as argument to .split() method
return splitted;
}

示例输出:

D 1 A A 2000 F 10 G 10 A 

关于java - 是否可以在Java中生成自定义字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50232347/

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