Android Studio Java - 如何使用随机数组而不重复?
Android Studio Java - How do I use a random array without repeating?
我有一组随机消息,但我想要它,这样它就不会选择已经被选择的消息,然后在所有消息都被选择后重置。
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));
}
您可以为删除一条消息的消息 getter 编写逻辑,如果没有消息可用,则重新填充:
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);
}
我有一组随机消息,但我想要它,这样它就不会选择已经被选择的消息,然后在所有消息都被选择后重置。
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));
}
您可以为删除一条消息的消息 getter 编写逻辑,如果没有消息可用,则重新填充:
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);
}