随机随机播放按钮

时间:2016-03-14 02:38:11

标签: java android random

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

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

另外,如何防止随机数发生器两次选择相同的值? (即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]);
谢谢你的时间。

2 个答案:

答案 0 :(得分:1)

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之间的随机整数。按照现在的方式,如果random.nextInt(3)返回2,则button2的文本将被设置为按钮[1-2]又名按钮[-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

答案 1 :(得分:0)

  1. 您是否尝试过setSeed
  2. 如果您可以shuffle进行随机化,为什么要自己进行随机化。
相关问题