Results 1 to 5 of 5
- 12-31-2009, 07:12 AM #1
Member
- Join Date
- Aug 2009
- Posts
- 48
- Rep Power
- 0
How to generate 8 character long alphanumeric string
Hi,
Hope you all will be fine.I want to generate 8 character long alphanumeric string and for this i used this line of code
But the problem is this gives me 16 character long string how can i reduce it to 8 characters, please helpJava Code:System.out.println(Long.toHexString(Double.doubleToLongBits(Math.random())));
Thank you
- 12-31-2009, 07:35 AM #2
Senior Member
- Join Date
- Aug 2009
- Posts
- 2,388
- Rep Power
- 6
But you won't get all the alphanumerics with that.
Better have a look at
Java Code:String alphaNumerics = "qwertyuiopasdfghjklzxcvbnm1234567890"; String t = ""; for (int i = 0; i < 8; i++) { t += alphaNumerics.charAt((int) (Math.random() * alphaNumerics.length())); } System.out.println(t);
- 12-31-2009, 07:58 AM #3
Member
- Join Date
- Aug 2009
- Posts
- 48
- Rep Power
- 0
Hi :),
Thank you very much. You post a nice code because it's very very simple and up to my expectations, but i found this code, it's also very easy. I am posting it here so others can also look at it if they want to like it.
Thank you:)Java Code:public class AlphaNumeric { private static final String ALPHA_NUM ="0123456789abcdef"; public static String getAlphaNumeric(int len) { StringBuffer sb = new StringBuffer(len); for (int i=0; i<len; i++) { int ndx = (int)(Math.random()*ALPHA_NUM.length()); sb.append(ALPHA_NUM.charAt(ndx)); } return sb.toString(); } public static void main(String[] args) { System.out.println(" character long: " +getAlphaNumeric(8)); /** * Another method String alphaNumerics = "qwertyuiopasdfghjklzxcvbnm1234567890"; String t = ""; for (int i = 0; i < 8; i++) { t += alphaNumerics.charAt((int) (Math.random() * alphaNumerics.length())); } System.out.println("with new code: " + t); */ } }
- 12-31-2009, 08:02 AM #4
Senior Member
- Join Date
- Aug 2009
- Posts
- 2,388
- Rep Power
- 6
If you want to use a buffer for the result then use StringBuilder instead of StringBuffer.
StringBuilder is faster.
- 12-31-2009, 11:05 AM #5
Senior Member
- Join Date
- Dec 2008
- Location
- Hong Kong
- Posts
- 473
- Rep Power
- 5
StringBuilder and StringBuffer are the same, except StringBuffer is thread safe.
Similar Threads
-
Help with creating a variable from a character in string
By Mayur in forum New To JavaReplies: 7Last Post: 10-12-2009, 11:16 PM -
Generate a random code 4 letters long
By bl00dr3d in forum New To JavaReplies: 9Last Post: 04-06-2009, 05:32 AM -
how to get next character/string
By doha786 in forum New To JavaReplies: 3Last Post: 03-28-2009, 04:04 AM -
Inserting string with slash character into database
By Java Tip in forum Java TipReplies: 0Last Post: 02-07-2008, 08:57 AM -
Error: convert from String to long
By bbq in forum New To JavaReplies: 1Last Post: 06-29-2007, 07:23 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks