SmarterThings.co.uk
Things... Smarter!
Subscribe to SmarterThings.co.uk RSS feedView a HTML version of the SmarterThings.co.uk RSS feedJava > Snippets > Other > Random Characters
Random Characters
Vote for a 1 star ratingVote for a 2 star ratingVote for a 3 star ratingVote for a 4 star ratingVote for a 5 star rating
Avg: 4.0
As part of some coding I am doing for the website, I required a method of generating a random 10 character string from numbers and uppercase characters. I wanted to only restrict to those characters which didn't look like other characters, so a simply random plus ASCII '0' was out of the question. The solution is however quite simple. We just create a String with all of the characters we want to use, and select a random character from that String,
String charset = "2346789ABCDEFGHJKMNPQRTWXZ"; StringBuffer sb = new StringBuffer(10); for (int i = 0; i < 10; i++) { sb.append(charset.charAt((int)(Math.random()*charset.length()))); } String code = sb.toString();
Created by David Hayes on Fri, 27 Jan 2006 23:36:00