random - JAVA Can someone explain this code for me? Auto-Gen -


i found these codes online at:

http://www.java2s.com/code/java/security/generatearandomstringsuitableforuseasatemporarypassword.htm

but not sure codes' logic.

public static string generaterandompassword() {        string letters = "abcdefghjkmnpqrstuvwxyzabcdefghjkmnpqrstuvwxyz23456789";        string pw = "";       (int i=0; i<password_length; i++)       {           int index = (int)(random.nextdouble()*letters.length());           pw += letters.substring(index, index+1);        }       return pw; } 

can explain 2 lines of codes me can understand better?

int index = (int)(random.nextdouble()*letters.length()); pw += letters.substring(index, index+1);  

thank you. :d

int index = (int)(random.nextdouble()*letters.length()); generates random double greater or equal 0.0 , less 1.0. multiples result length of string of acceptable letters. essentially, in these 2 steps, have number between 0 (inclusive) , total number of valid "letters", double, has decimal part. number casted int (a whole number) , saved index variable.

pw += letters.substring(index, index+1); concatenates pw substring of letters string. substring begins @ index determined line above , ends @ index + 1 (not including character @ index + 1). essentially, part makes substring of 1 character @ index determined random integer generated above. concatenates onto existing pw string.

example of steps:

int index = (int)(random.nextdouble()*letters.length());:

  1. random.nextdouble() => 0.51
  2. letters.length() => 60
  3. random.nextdouble()*letters.length() => 30.6
  4. (int)(random.nextdouble()*letters.length()) => 30

pw += letters.substring(index, index+1);:

  1. letters.substring(index, index+1) => "h"
  2. pw += letters.substring(index, index+1) => "" + "h" => "h"

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -