如何使用随机数组而不重复?

oiopk7p5  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(368)

我有一个随机消息数组,但我希望它不会选择一个已经被选择的消息,然后在所有消息被选择后重置。

public void showRandomMsg(){
        shuffleMsg();
        answer1.setText((messageArray[0].getmAns()));
        message2.setText((messageArray[0].getmMsg()));
        toyView1.setImageResource(messageArray[0].getmImage());
    }

Messages m01 = new Messages(R.drawable.crown1, "Mesage 0 A","Message 0 B");
Messages m02 = new Messages(R.drawable.crown2,"Mesage 1 A","Message 1 B");
Messages m03 = new Messages(R.drawable.crown3,"Mesage 2 A","Message 2 B");
Messages m04 = new Messages(R.drawable.crown4,"Mesage 3 A","Message 3 B");
Messages m05 = new Messages(R.drawable.crown5,"Mesage 4 A","Message 4 B");

Messages [] messageArray=new Messages[]{
        m01, m02, m03, m04, m05
};

public void shuffleMsg(){
    Collections.shuffle(Arrays.asList(messageArray));

}
fslejnso

fslejnso1#

您可以为删除一条消息的消息获取程序编写逻辑,如果没有可用的消息,则重新填充:

List<Messages> messageList;

public void showRandomMsg(){
    if (Objects.isNull(messageList) || messageList.size() == 0) {
        refillMsg();
    }
    answer1.setText(messageList.remove(0).getmAns());
    message2.setText(messageList.remove(0).getmMsg());
    toyView1.setImageResource(messageList.remove(0).getmImage());
}

public void refillMsg() {
    messageList = Arrays.asList(new Messages[] {
        m01, m02, m03, m04, m05
    });
    Collections.shuffle(messageList);
}

相关问题