【问题标题】:randomly shuffle text from resources从资源中随机打乱文本
【发布时间】:2014-09-23 11:45:26
【问题描述】:

我如何随机打乱这个数组? 基本上我有 4 个按钮,我想随机更改按钮的文本。 例如:按钮有黑色、红色、黄色、绿色,当我点击任何一个按钮时,我需要随机更改这些文本。

这是我的代码

final int[] name={ R.string.text1,R.string.text2,R.string.text3,R.string.text4};
List<Integer> shuffle = new ArrayList<Integer>(Arrays.asList(name));

for(int i = 0; i <shuffle.Count(); i++)
 b[i].Text = shuffle[i];

【问题讨论】:

标签: java android random


【解决方案1】:

你可以使用 Collections.shuffle(List) 方法

final Integer[] name={ 1, 2, 3, 4};
List<Integer> shuffle = new ArrayList<Integer>(Arrays.asList(name));

for(int i = 0; i <shuffle.size(); i++) {
    Collections.shuffle(shuffle);
    for (int j = 0; j < shuffle.size(); j++) {
        System.out.print(shuffle.get(j) + " ");
    }
    System.out.println();
}

在本例中,输出为:

4 3 1 2 
2 1 4 3 
3 1 2 4 
3 1 2 4 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多