gpt4 book ai didi

java - 如何在 JAVA 中使用 math.random 用另一个数组中的字符填充数组

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

我正在尝试使用包含七个字符的数组中的四个随机字符填充一个新数组。这可能吗?我似乎找不到正确的方法。

这是我尝试过的,但出现错误,

char charactersAllowed[] = {'a','b','c','d','e','f','g'};
char currentCharacters[] = charactersAllowed[ (int)
(Math.random() * 4) ];

错误:类型不兼容:char 无法转换为 char[ ]

最佳答案

这是因为您正在访问数组中的单个字符。

通过一个简单的循环获取 4 个随机字符:

char[] currentCharacters = new char[4];
for(int i = 0; i < currentCharacters.length; i++) {
currentCharacters[i] = charactersAllowed[(int) (Math.random() * 4)];
}

另请注意,最好将数组定义为 Object[] 变量,而不是 Object 变量[]

关于java - 如何在 JAVA 中使用 math.random 用另一个数组中的字符填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50091064/

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