2012-12-08 35 views
2

美好的一天!我是編程的初學者,我一直在編寫一個程序。它使用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]); 
     } 
    } 
} 
+0

無關,但考慮速記數組初始化或至少使用普通的老式整數而不是在變量上進行數學計算 - 在我確信我已經知道它試圖做什麼之前,必須多次看一下。 –

+0

http://www.vogella.com/articles/JavaAlgorithmsShuffle/article.html,然後遍歷數組 – zapl

+0

@DaveNewton我這樣做是因爲我需要給該數組分配一個「int」使其成爲隨機數。 – ninadeleon

回答

0

試試這個

Random randnum = new Random (System.currentTimeMillis()); 
    java.util.HashSet<Integer> myset = new java.util.HashSet<Integer>(); 
    for (int count = 1; count <=5; count++){ 
     while(true) { 
      a = randnum.nextInt (5) ; 
      if(!myset.contains(a)) { myset.add(new Integer(a)); break;} 
     } 
     System.out.println ("Question # " + count + "\n" + arr [a]); 
    } 
+0

謝謝你。它對我的程序起作用!非常感謝!! :d – ninadeleon

5

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)); 
    } 
} 
+0

+1 - 注意**真**隨機數可以重複。 –

+0

感謝您的回答。它看起來不錯,但是當我將它粘貼到NetBeans上時發生錯誤。我也不知道如何使用集合和列表。有沒有比這更簡單的代碼? – ninadeleon

+0

@NinaDeLeon我剛剛複製並將其粘貼到NetBeans,它工作正常。也許你需要修復你的導入(Ctrl + Shift + I)?坦率地說,這是最簡單的方法之一。 –