• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Password creation using rng.nextInt()

 
Mark Phylus
Greenhorn
Posts: 18
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I used rng.nextInt()to generate both username and password. The username is fine but the password contains wild character that I want to eliminate. How? Here is some code:
private void makePassWord()
{
int numEven = 0;
int numOdd = 0;
for(int k=0; k<4; k++)
{
numEven = rng.nextInt(65)+26; // any upper case letter or @
passWord += (char) numEven;
numOdd = rng.nextInt(49)+33; // any digitprintable character
// from 33 to 90
passWord += (char) numOdd;
}
}
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try:

With the old way, numEven = rng.nextInt(65)+26;, nextInt will return a value in the range 0-64. Adding 26 to it gives you a value in the range 26-90, which is not what you want.
With the new way, numEven = rng.nextInt(27)+64;, nextInt will return a value in the range 0-26, and adding 64 to that will give you a value in the range 64-90, which is the uppercase characters and '@'.
For the "numOdd", I changed the seed to 58 to give you the full 33-90 range.
[ March 31, 2004: Message edited by: Wayne L Johnson ]
 
Brian Pipa
Ranch Hand
Posts: 299
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's another way to do it. Put all characters that you consider legal/valid into an array and just randomly choose characters out of the array:



Brian
[ April 05, 2004: Message edited by: Brian Pipa ]
 
Mark Phylus
Greenhorn
Posts: 18
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks guys.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic