2012-12-08 32 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)?坦率地说,这是最简单的方法之一。 –