Java Math random String generate

Description

Java Math random String generate


public class Main {

   public static void main(String[] args) {

      System.out.println(getRandomString(10));
      System.out.println(getRandomString(20));
   }// w  w  w .j a va  2  s . co  m

   /**
    * Generate a random String with maxlength random characters found in the ASCII
    * table between 33 and 122 (so it contains every lowercase / uppercase letters,
    * numbers and some others characters
    */
   public static String getRandomString(int maxlength) {
      String result = "";
      int i = 0, n = 0, min = 33, max = 122;
      while (i < maxlength) {
         n = (int) (Math.random() * (max - min) + min);
         if (n >= 33 && n < 123) {
            result += (char) n;
            ++i;
         }
      }
      return (result);
   }

}



PreviousNext

Related