2

良い一日!私はプログラミングの初心者で、プログラムに取り組んできました。import java.util.Random質問を特定の順序でランダムに表示したいので、これを使用します。しかし、問題と唯一の問題は、質問が繰り返されることです。たとえば、「あなたは幸せですか?」「iPhone5が欲しいですか?」と3回尋ねられます。聞かれることさえありません。すべての質問を順不同で表示し、同じ質問を何度も選択しないようにするにはどうすればよいですか?これまでのところ、これは私が持っているものです。

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 に答える