Java char type generate random character

Description

Java char type generate random character

class RandomCharacter {
  /** Generate a random character between ch1 and ch2 */
  public static char getRandomCharacter(char ch1, char ch2) {
    return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
  }/*from   ww w  .  j a  va2s.  c  o  m*/

  /** Generate a random lowercase letter */
  public static char getRandomLowerCaseLetter() {
    return getRandomCharacter('a', 'z');
  }

  /** Generate a random uppercase letter */
  public static char getRandomUpperCaseLetter() {
    return getRandomCharacter('A', 'Z');
  }

  /** Generate a random digit character */
  public static char getRandomDigitCharacter() {
    return getRandomCharacter('0', '9');
  }

  /** Generate a random character */
  public static char getRandomCharacter() {
    return getRandomCharacter('\u0000', '\uFFFF');
  }
}

public class Main {
  /** Main method */
  public static void main(String args[]) {
    // Print random characters between 'a' and 'z', 25 chars per line
    for (int i = 0; i < 10; i++) {
      char ch = RandomCharacter.getRandomLowerCaseLetter();
      System.out.println(ch);
    }
  }
}



PreviousNext

Related