美好的一天!我是編程的初學者,我一直在編寫一個程序。它使用import java.util.Random
,因爲我希望我的問題以任意順序隨機出現。但問題和唯一的問題是這個問題重複。例如,「你快樂嗎?」被問了三次,「你想要iPhone 5嗎?」甚至沒有被問到。我應該怎麼做才能以不特定的順序顯示所有問題,因此它不會多次選擇相同的問題?到目前爲止,這就是我所擁有的。我將如何得到不使用`import java.util.Random`的重複結果?
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]);
}
}
}
無關,但考慮速記數組初始化或至少使用普通的老式整數而不是在變量上進行數學計算 - 在我確信我已經知道它試圖做什麼之前,必須多次看一下。 –
http://www.vogella.com/articles/JavaAlgorithmsShuffle/article.html,然後遍歷數組 – zapl
@DaveNewton我這樣做是因爲我需要給該數組分配一個「int」使其成爲隨機數。 – ninadeleon