【问题标题】:Is there a more effective way to give random values to Button elements in Android Studio?有没有更有效的方法来为 Android Studio 中的 Button 元素提供随机值?
【发布时间】:2021-02-22 21:42:07
【问题描述】:

我的 Activity 中连续有 4 个 Button 元素。我有四个统计值,我想在每次按下按钮后将这些值随机分配给按钮。

目前我编写了一个生成器方法,它生成 4 个不同的值并将按钮值设置为它们。我想知道,也许在 Android 中有更有效的工具来完成这项任务?

生成器:

public void generator(View view) {
        int one = new Random().nextInt(4);
        int two;
        do {
            two = new Random().nextInt(4);
        } while (two == one);
        int three;
        do {
            three = new Random().nextInt(4);
        } while (three == one || three == two);
        int four;
        do {
            four = new Random().nextInt(4);
        } while (four == one || four == two || four == three);
        buttonOnebutton.setText(String.valueOf(one));
        buttonTwobutton.setText(String.valueOf(two));
        buttonThreebutton.setText(String.valueOf(three));
        buttonFourbutton.setText(String.valueOf(four));
    }

【问题讨论】:

    标签: java android random


    【解决方案1】:

    这可以通过其他方式完成。创建一个整数集合(列表或数组)并打乱它。最后你会得到随机顺序的唯一整数集合。


    在某个时间点创建一个集合,最好在类初始化时创建一次。

    int size = 4;
    List<Integer> numbers = new ArrayList<>(size);
    for (int i = 0; i < size; i++) {
        numbers.add(i);
    }
    

    随机播放并将文本分配给按钮

    public void generator(View view) {
        Collections.shuffle(numbers); // java.util.Collections
        buttonOnebutton.setText(String.valueOf(numbers.get(0));
        buttonTwobutton.setText(String.valueOf(numbers.get(1)));
        ...
    }
    

    集合可以包含您需要的任何内容,例如字符串

    List<String> list = Arrays.asList("first", "second", "third", "fourth");
    // list = ["first", "second", "third", "fourth"]
    Collections.shuffle(list);
    // at this point list will be in random order, 
    // e.g. list = ["third", "fourth", "second", "first"]
    

    【讨论】:

    • 感谢您的想法,从现在开始我将使用 shuffle 方法,它看起来也适合我当前的任务。
    猜你喜欢
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    相关资源
    最近更新 更多