Perry Smith

Java Questions & Answers

Home / Java Q & A Archive Page 3 / Java Q & A Archive

Randomised variables
 Wednesday, 13-Jan-99 23:49:12

      139.230.128.6 writes:

      Could somebody please tell me if Java supports a function that could select a certain
      phrase or string randomly from a list (or array?) already provided ? ARe there any
      examples around which I could learn from ?

      As the wording of my question might suggest, I am quite new to Java.

      Martin

Response
Re: Randomised variables
 Thursday, 14-Jan-99 01:31:27

      152.202.73.169 writes:

      I believe the Random API is in the java.util package. So, code to choose a random selection would go like this.

      import java.util.Random;
      import java.lang.Math;

      class ProblemSolver
      {
      .
      .
      .
      String strArray[] = new String[SOMEsIZE];
      Random rndNum = new Random();
      String strRandom;
      int iRndIndex;
      .
      .
      .
      iRndIndex = Math.round(rndNum.nextFloat());
      strRandom = strArray[iRndIndex];
      .
      .
      .
      }

      MikeD


Home / Java Q & A Archive Page 3 / Java Q & A Archive