1. Are you ready for the Galaxy S20? Here is everything we know so far!

Calling Random Classes

Discussion in 'Android Development' started by chpsrmne, Aug 31, 2011.

  1. chpsrmne

    chpsrmne Lurker
    Thread Starter

    Im currently working on an app that will work kind of like a quiz. What I am trying/hoping to accomplish is to have a random sound file played and have a couple of options to correctly match to the sound clip. The biggest problem I am having is calling the random sound file. I could get them to go in order but after a few times you could just memorize the answers. I was wondering if there was a way to randomly call a class or if there is a better way that I may not be thinking of. Kind of hit a wall and any help would be appreciated. Thanks in andvance


    1. Download the Forums for Android™ app!


  2. Velvet Void

    Velvet Void Lurker

    You could use Java's Random Class and use its nextInt(n) function, with a switch statement to choose the next sound file and questions.

    Example code: (I didn't run this, should work though)

    Code (Text):
    1. import java.util.Random;
    3. public class YourClass
    4. {
    5.      private static final int MAX_NUMBER=5; //number of sounds
    6.      private Random rnd= new Random(); //declaring random number generator and initializing it
    8.      private void choose ()
    9.      {
    10.           //choose a random number from 0 to (1 below MAX_NUMBER)
    11.           switch(rnd.nextInt(MAX_NUMBER))
    12.           {
    13.                 case 0:
    14.                           // if 1st sound is picked, do stuff
    15.                          break;
    16.                 case 1:
    17.                           // if 2nd sound is picked, do stuff
    18.                          break;
    19.                 case 2:
    20.                           // if 3rd sound is picked, do stuff
    21.                          break;
    22.                 case 3:
    23.                           // if 4th sound is picked, do stuff
    24.                          break;
    25.                 case 4:
    26.                           // if 5th sound is picked, do stuff
    27.                          break;
    28.                 //keep going until you have a case for each sound
    29.                 //in this case with MAX_NUMBER at 5, I would stop at 4
    30.           }
    31.      }
    32. }
    Just add in the declaration and a similar method into the class you're using and that should work
  3. chpsrmne

    chpsrmne Lurker
    Thread Starter

    seems lilke it could work, ill give it a try.

    Thanks for the suggestion!


Share This Page