nin*_*eon 2 java arrays string random netbeans
美好的一天!我是编程的初学者,我一直在研究一个程序.它的使用import java.util.Random
是因为我希望我的问题不按特定顺序随机出现.但问题和唯一的问题是问题重复.例如,"你快乐吗?" 被问过三次,"你想要iPhone 5吗?" 甚至没有问过.我该怎么做才能以不特定的顺序显示所有问题,所以它不会多次选择相同的问题?到目前为止,这就是我所拥有的.
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]);
}
}
}
Run Code Online (Sandbox Code Playgroud)
1到5之间的真正随机整数几乎肯定会有大量的重复数字.如果您只想以随机顺序放置数组元素,那么您应该使用Collections.shuffle
:
public static void main(String[] args) {
String[] array = {
"Are you happy? \na. yes\t\tb. no\nc. maybe\td. no comment",
"Did you eat breakfast? \na. yes\t\tb. no\nc. maybe\td. no comment",
"Have you watched tv? \na. yes\t\tb. no\nc. maybe\td. no comment",
"Do you want iPhone 5? \na. yes\t\tb. no\nc. maybe\td. no comment",
"Will you have iPad mini? \na. yes\t\tb. no\nc. maybe\td. no comment"
};
List<String> items = Arrays.asList(array);
Collections.shuffle(items);
for (int index = 0; index < 5; index++) {
System.out.println("Question # " + (index + 1) + "\n" + items.get(index));
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
263 次 |
最近记录: |