数组如何在使用“导入java”时获得不重复的结果。util。随机的`?
你好!我是一个编程初学者,我一直在做一个程序。它使用import java.util.Random
,因为我希望我的问题不按特定顺序随机出现。但问题是,唯一的问题是,问题重复了。例如,“你快乐吗?”被问了三次“你想要iphone5吗?”甚至没有人问。我应该怎么做才能把所有的问题按不特定的顺序展示出来,这样它就不会多次选择同一个问题了?到目前为止,这就是我所拥有的
import java.util.Random;
public class RandomQuiz {
public static void main (String args []){
int a, b=0;
String arr [];
arr = new String [5];
a = b;
arr [a] = "Are you happy? \na. yes\t\tb. no\nc. maybe\td. no comment";
a = b+1;
arr [a] = "Did you eat breakfast? \na. yes\t\tb. no\nc. maybe\td. no comment";
a = b+2;
arr [a] = "Have you watched tv? \na. yes\t\tb. no\nc. maybe\td. no comment";
a = b+3;
arr [a] = "Do you want iPhone 5? \na. yes\t\tb. no\nc. maybe\td. no comment";
a = b+4;
arr [a] = "Will you have iPad mini? \na. yes\t\tb. no\nc. maybe\td. no comment";
//prints array values in random
Random randnum = new Random ();
for (int count = 1; count <=5; count++){
a = randnum.nextInt (5);
System.out.println ("Question # " + count + "\n" + arr [a]);
}
}
}
# 1 楼答案
试试这个
# 2 楼答案
一个介于1和5之间的真正随机整数几乎肯定会有大量重复的数字。如果只想将数组的元素按随机顺序排列,那么应该使用
Collections.shuffle
: