go to previous page   go to home page   go to next page hear noise highlighting

Answer:

Yes. But I think that is easier to build the string in three steps.


Building the Password

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. This matches the range of character indexes in the 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.)


QUESTION 16:

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;

go to previous page   go to home page   go to next page