[java] 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.

This question is related to java android random

The answer is


  1. Pick a random number between [0, x), where x is the number of different symbols. Hopefully the choice is uniformly chosen and not predictable :-)

  2. Now choose the symbol representing x.

  3. Profit!

I would start reading up Pseudorandomness and then some common Pseudo-random number generators. Of course, your language hopefully already has a suitable "random" function :-)


Using some simple command line (bash scripting):

$ cat /dev/urandom | tr -cd 'a-z0-9,.?/\-' | head -c 30 | xargs
t315,qeqaszwz6kxv?761rf.cj/7gc

$ cat /dev/urandom | tr -cd 'a-z0-9,.?/\-' | head -c 1 | xargs
f
  • cat /dev/urandom: get a random stream of char from the kernel
  • tr: keep only char char we want
  • head: take only the first n chars
  • xargs: just for adding a '\n' char

Why reinvent the wheel? RandomStringUtils from Apache Commons has functions to which you can specify the character set from which characters are generated. You can take what you need to your app:

http://kickjava.com/src/org/apache/commons/lang/RandomStringUtils.java.htm


Here is code for secure, easy, but a little bit more expensive session identifiers.

import java.security.SecureRandom;
import java.math.BigInteger;

public final class SessionIdentifierGenerator
{

  private SecureRandom random = new SecureRandom();

  public String nextSessionId()
  {
    return new BigInteger(130, random).toString(32);
  }

}

Random random = new Random();
int n = random.nextInt(69) + 32;
if (n > 96) {
    n += 26;
}
char c = (char) n;

I guess it depends which punctuation you want to include, but this should generate a random character including all of the punctuation on this ASCII table. Basically, I've generated a random int from 32 - 96 or 123 - 126, which I have then casted to a char, which gives the ASCII equivalent of that number. Also, make sure youimport java.util.Random


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++) {
        System.out.print(alphabet.charAt(r.nextInt(N)));
    }

See below link : http://www.asciitable.com/

public static char randomSeriesForThreeCharacter() {
    Random r = new Random();
    char random_3_Char = (char) (48 + r.nextInt(47));
    return random_3_Char;
}

Now you can generate a character at one time of calling.


You should first make a String that holds all of the letters/numbers that you want.
Then, make a Random. e. g. Random rnd = new Random;
Finally, make something that actually gets a random character from your String containing your alphabet.
For example,

import java.util.Random;

public class randomCharacter {
    public static void main(String[] args) {
        String alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ?/.,";
        Random rnd = new Random();
        char char = alphabet.charAt(rnd.nextInt(alphabet.length()));
        // do whatever you want with the character
    }
}

See this.
It's where I got this info from.


random char package com.company;

         import java.util.concurrent.ThreadLocalRandom;

         public class Main {

            public static void main(String[] args) {
            // write your code here
                char hurufBesar =randomSeriesForThreeCharacter(65,90);
                char angka = randomSeriesForThreeCharacter(48,57);
                char simbol = randomSeriesForThreeCharacter(33,47);
                char hurufKecil= randomSeriesForThreeCharacter(97,122);
                char angkaLagi = randomSeriesForThreeCharacter(48,57);

                System.out.println(hurufBesar+" "+angka+" "+simbol+" "+hurufKecil+" "+angkaLagi);
            }

            public static char randomSeriesForThreeCharacter(int min,int max) {
                int randomNumber = ThreadLocalRandom.current().nextInt(min, max + 1);
                char random_3_Char = (char) (randomNumber);
                return random_3_Char;
             }
         }

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to random

How can I get a random number in Kotlin? scikit-learn random state in splitting dataset Random number between 0 and 1 in python In python, what is the difference between random.uniform() and random.random()? Generate random colors (RGB) Random state (Pseudo-random number) in Scikit learn How does one generate a random number in Apple's Swift language? How to generate a random string of a fixed length in Go? Generate 'n' unique random numbers within a range What does random.sample() method in python do?