gpt4 book ai didi

java - 随机排列按钮 android

转载 作者:行者123 更新时间:2023-12-01 10:14:31 26 4
gpt4 key购买 nike

正在进行单词测验 game 。该应用程序通过 API 获取定义和三个单词,然后将它们添加到 ui 中(如图所示)。对于 TextView 中显示的定义,其中 2 个单词的答案是错误的。

因此在 onPostExecute 方法中创建了一个字符串数组来保存所有按钮,然后尝试对该数组进行随机化,但程序每次都会生成相同的结果。

此外,如何防止随机发生器两次选择相同的值?(即 2 个具有相同名称的按钮)

 String[] buttons = new String[]{finalword,finaldummy1,finaldummy2};
int first = random.nextInt(1);


button1.setText(buttons[first]);
button2.setText(buttons[1-first]);
button3.setText(buttons[2-first]);

感谢您的宝贵时间。

最佳答案

Random 类的 .nextInt(int n) 方法返回 0(含)和 n(不包括)之间的随机十进制数。由于示例中的 n 为 1,因此该方法将始终随机生成 0 到 1 之间的数字(不包括 1)。将小数转换为 int 后,小数点右侧的所有数字都会被删除。例如,random.nextInt(1) 可能返回 0.654,它会转换为整数零。因此,该方法将始终返回 0,因为它永远不会返回大于 1 的小数。因此解决方案只需将 random.nextInt(1) 更改为 random.nextInt(3) 因为你想要一个 0 到 2 之间的随机整数(含 0 和 2)。按照你现在的方式,如果 random.nextInt(3) 返回 2,那么button2的文本将被设置为buttons[1-2]又名buttons[-1],这将给出错误。因此,您应该使用 Math 类中的绝对值函数。

 String[] buttons = new String[]{finalword,finaldummy1,finaldummy2};
int first = random.nextInt(3);


button1.setText(buttons[first]);
button2.setText(buttons[Math.abs(first-1)]);
button3.setText(buttons[Math.abs(first-2) + (first == 1 ? 1 : 0]);
//the ? operator is a ternary operator
//+ (first == 1 ? 1 : 0) translates to "if first is one, then add 1, if not, add 0

关于java - 随机排列按钮 android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35978685/

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