将字符添加到字符串中

Uko*_*koM 2 java string char

import java.util.Random;

public class PasswordRandomizer {
    // Define the variables
    private Random random = new Random();
    private int passwordLength;
    private String password = "";

    public PasswordRandomizer(int length) {
        // Initialize the variable
        this.passwordLength = length;
    }

    public String createPassword() {
        // write code that returns a randomized password
        for(int i = 0; i < this.passwordLength; i++){
            int j = random.nextInt();
            char symbol = "abcdefghijklmnopqrstuvwxyz".charAt(j);
            this.password = this.password + symbol; 
        }
        return this.password;
    }
}
Run Code Online (Sandbox Code Playgroud)

如何在字符串中添加字符,我试过这个,但是我收到了这个错误:

"线程中的异常"主"java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-414383904".

Xav*_*tte 7

这是因为random.nextInt()返回-2,147,483,648和2,147,483,647之间的值.

你想要的是什么 random.nextInt("abcdefghijklmnopqrstuvwxyz".length())

我也会分配"abcdefghijklmnopqrstuvwxyz"一个常数.

private final static String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

Char randomChar = ALPHABET.charAt(random.nextInt(ALPHABET.length()));
Run Code Online (Sandbox Code Playgroud)

  • 实际上是[-2,147,483,648,2,147,483,647]的范围 (4认同)