vendredi 30 septembre 2016

With Sound Arrays, how do I play random unique sounds?

So far, this code sounds out the words "This is a test" in random order, but the words can repeat more than once. myWordArray is a static Sound array set up in the program that reads splice points from the specific sound.

public void playRandomOrder(int totalWords, int pause) throws InterruptedException {
    Random random = new Random(); // Random number generator for array shuffle
    for (int i =0; i< numWords; i++) {
        int randomPosition = random.nextInt(totalWords); // how many words to sound out (4)
        Sound temp = myWordArray[i];
        myWordArray[i] = myWordArray[randomPosition];
        myWordArray[randomPosition] = temp;
        myWordArray[i].blockingPlay();
        Thread.sleep(pause); // 320 m.seconds, as listed in main method parameter
}
}

I want it to be so that the words can play randomly, but without a single word repeating. For example "This a test is" instead of "This is is test" Here is what I have so far for the unique random words...

public void playRandomUnique(int pause) throws InterruptedException {
    final Random random = new Random();
    List<Sound> list = Arrays.asList(myWordArray);
    Collections.sort(list, new Comparator<Sound>(){
        @Override
        public int compare(Sound o1, Sound o2){
            return random.nextInt() % 2 == 0 ? 1 : -1;
        }
    });
    list.toArray(myWordArray);
    for (Sound sound: myWordArray)
        sound.blockingPlay();
        Thread.sleep(pause);

}

This however, results in "Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!" and no sound plays out when I run it in main.




Aucun commentaire:

Enregistrer un commentaire