I am trying to create a program that generates random passwords using the characters A-Z and the numbers 0-9. It will also have an input of what you want the length of the password to be.

What I don't know how to do is to create a method to choose random, arbitrary characters/ numbers.

Are there any objects that specialize in selecting random characters?

Recommended Answers

All 8 Replies

I am trying to create a program that generates random passwords using the characters A-Z and the numbers 0-9. It will also have an input of what you want the length of the password to be.

What I don't know how to do is to create a method to choose random, arbitrary characters/ numbers.

Are there any objects that specialize in selecting random characters?

You may simply have to create your own.

The concept isn't too hard though.

In Ascii A is 65. I'd assume Z would be 65 + 25 (or maybe 26... too tired to think really).
Once the number is chosen do a cast to the char type.

import java.util.*;

public class Generator{

	private Random rgen = new Random();
	private byte decision, numValue;
	private char charValue;

	public static void main(String... args){
		System.out.println(new Generator().gen(9));
	}

	public String gen(int length){
		StringBuilder sb = new StringBuilder();
		while(sb.length() < length){
			decision = (byte)rgen.nextInt(2);
			numValue = (byte)rgen.nextInt(10);
			charValue = (char)(rgen.nextInt(25) + 65);
			sb.append( (decision%2 == 0) ? ( charValue + "" ) : ( numValue + "") );
		}
		return sb.toString();
	}
}

String array of A-Z characters and integers 0-9, which makes 36 elements (26 letters plus 10 numbers). Create random number generator between 0-35 with "i" loop to get password of certain length. Wouldn't be that the simplest solution?

i have something like that

String array of A-Z characters and integers 0-9, which makes 36 elements (26 letters plus 10 numbers). Create random number generator between 0-35 with "i" loop to get password of certain length. Wouldn't be that the simplest solution?

I was thinking about that, but I still don't know how to write line to generate a random number 0-35. I just need that one line that generates the randomness, arg.

Math.random()

The above returns a random number between 0 and 1

a pseudorandom double greater than or equal to 0.0 and less than 1.0.

Math.random()

HOw to get random number between 0 -35

Random rand = new Random();
int num = rand.nextInt(35);

Math.random()

The above returns a random number between 0 and 1


Math.random()

Yes, and since it's a random number between 0 and 1 you can use this to your advantage by multiplying the result with a number that you want to be the "range" for randomness.

Math.random() * 35 generates a number that may be >= 0 or < 35.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.