|
-
May 27th, 2007, 07:53 AM
#1
Thread Starter
New Member
Choosing a random vector and choosing a random value
Hi,
I'm working on a program that can generate random passwords. I've got a JComboBox in which the user can choose the PasswordLength. Then, when the user clicks on the Generate-button, a random password is generated.
I've got 3 vectors:
The first vector contains digits from 0 to 9.
The second vector contains the alphabet in lower case.
The third vector contains the alphabet in upper case.
When the user presses the Generate-button, the method GeneratePassword() is invoked. But I don't exactly know how to write that method.
For every place in the password, the program must choose a random vector out of the three vectors mentioned above, to pick a value from.. and then choose a random value. For the next place in the password, this operation must be repeated.
The method GeneratePassword() is empty now:
Code:
public String GeneratePassword() {
for(int i = 0; i < Integer.parseInt((String)cPasswordLength.getSelectedItem()); i++) {
}
}
Using a for-statement, the method should go to the next place in the password to be generated.
So, anyone wants to help?
-
Jun 6th, 2007, 01:41 PM
#2
Re: Choosing a random vector and choosing a random value
Code:
import java.util.Random;
import java.util.Vector;
/**
*
* @author ComputerJy
*/
public class PasswordCreator
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
PasswordCreator pc=new PasswordCreator();
System.out.printf("You password is: %s\n", pc.getPassword(10));
}
private Vector<Character> vChar;
private Vector<Character> vCaps;
private Vector<Character> vNumbers;
private Random rand;
private void InitVectors()
{
vChar=new Vector<Character>();
for(char c='a';c<='z';c++)
{
vChar.add(new Character(c));
}
vCaps=new Vector<Character>();
for(char c='A';c<='Z';c++)
{
vCaps.add(new Character(c));
}
vNumbers=new Vector<Character>();
for(int i=0;i<10;i++)
{
vNumbers.add(Integer.toString(i).charAt(0));
}
rand=new Random();
}
public String getPassword(int passwordLength)
{
if(vChar==null||vCaps==null||vNumbers==null)InitVectors();
StringBuilder sb=new StringBuilder();
for(int i=0;i<passwordLength;i++)
{
switch(rand.nextInt(3))
{
case 0:
sb.append(vChar.elementAt(rand.nextInt(vChar.size())));
break;
case 1:
sb.append(vCaps.elementAt(rand.nextInt(vCaps.size())));
break;
case 2:
sb.append(vNumbers.elementAt(rand.nextInt(vNumbers.size())));
break;
}
}
return sb.toString();
}
}
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|