【问题标题】:how set button text randomly without duplicates?如何随机设置按钮文本而不重复?
【发布时间】:2016-02-04 13:38:35
【问题描述】:

我想通过str数组随机设置按钮文本:

String str[] = { "1", "2", "3", "4", "5", "6" };
Button buttons[] = new Button[4];

        buttons[0] = (Button) findViewById(R.id.id1);
        buttons[1] = (Button) findViewById(R.id.id2);
        buttons[2] = (Button) findViewById(R.id.id3);
        buttons[3] = (Button) findViewById(R.id.id4);

for (int i = 0; i < 4; i++) {
        Random r = new Random();
        int x = r.nextInt(str.length); 
        buttons[i].setText(str[x]);
                    }

那么我怎样才能设置没有重复的按钮文本呢? 像这样的东西:

【问题讨论】:

  • 例如,构建一个 ArrayList 并将使用的字符串添加到其中。然后检查......
  • 不重复什么?
  • 尝试移动随机 r = new Random();到 for 循环之前。
  • 这个问题没有任何细节可以保证答案。

标签: android random


【解决方案1】:

你的问题不是很清楚。我想这可能是你想要的:

1) 将备用按钮文本放入数组、列表或方便的结构中。

2) 随机排列数组(或其他),使文本以随机顺序排列,不重复。

3) 按打乱顺序挑选文本以分配给按钮。

【讨论】:

  • 我认为,对于这组有限的文本,这将是更清洁的解决方案。
【解决方案2】:
        List<Integer> setNames = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            int x;
            do {
                Random r = new Random();
                x = r.nextInt(str.length);
            }while(setNames.contains(x));
            setNames.add(x);
            buttons[i].setText(str[x]);
        }

这是另一种可能性。足以进行四次迭代。

【讨论】:

    猜你喜欢
    • 2014-03-11
    • 1970-01-01
    • 2015-03-13
    • 2013-02-14
    • 1970-01-01
    • 2017-10-09
    • 2011-09-18
    • 2011-06-19
    • 1970-01-01
    相关资源
    最近更新 更多