2

再会!我是编程的初学者,我一直在研究一个程序。它使用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]);
        }
    }
}
4

2 回答 2

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));
  }
}
于 2012-12-08T02:36:54.540 回答
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]);
    }
于 2012-12-08T02:45:42.777 回答