Yes. But I think that is easier to build the string in three steps.
Next, the program builds the password:
String password = ""; int j = 0; while ( j<digits ) { password = password + choices.charAt( rand.nextInt( choices.length() ) ); j = j + 1; }
First the password is initialized to the empty string.
Then random characters, selected from choices
,
are appended to it, one-by-one.
The expression
rand.nextInt( choices.length() )
randomly picks an integer from 0 up to (but not including) the length of the choices
string.
Then that integer is used to select a character from the choices
string.
Say that the random integer were 7
. Then
choices.charAt( 7 )
is character number 7 in the string choices
, where counting starts at zero.
This character is appended to the password and the loop repeats.
(For more about string methods, see chapter 29.)
Examine this statement:
password = password + choices.charAt( rand.nextInt( choices.length() ) );
Four things happen in that one statement. This can be hard to keep track of. Is the following code fragment equivalent?
int range = choices.length(); int characterNumber = rand.nextInt( range ); char ch = choices.charAt( characterNumber ); password = password + ch;