Random character generator with a range of (A..Z, 0..9) and punctuation


I need to create a random character generator that return a single character. The character should range within the letters of the alphabet, numbers 0 through 9, and some characters like ,.?/-. Any example would be appreciated.

6/25/2010 12:51:49 PM

The easiest is to do the following:

  • Create a String alphabet with the chars that you want.
  • Say N = alphabet.length()
  • Then we can ask a java.util.Random for an int x = nextInt(N)
  • alphabet.charAt(x) is a random char from the alphabet

Here's an example:

    final String alphabet = "0123456789ABCDE";
    final int N = alphabet.length();

    Random r = new Random();

    for (int i = 0; i < 50; i++) {
6/25/2010 12:56:24 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow