无法生成固定大小的字母数字符号字符串

时间:2019-05-02 08:41:50

标签: java android

如果用户不知道自己的密码,我正在构建一个为用户建议强密码的应用。这个想法是,用户选择密码的大小(4个单选按钮),密码特征(4个复选框)并生成匹配。基于此选择,我正在尝试生成一个随机字符串:

private String generatedPassword(){
    int length = 0;
    StringBuilder generatedString = new StringBuilder();
    Random rand = new Random();

    if(radio4.isSelected()){length = 4;}
    else if(radio8.isSelected()){length = 8;}
    else if(radio12.isSelected()){length = 12;}
    else if(radio16.isSelected()){length = 16;}

    if(passwordABCD.isSelected()){totalCharacters += capitalLetters;}
    if(passwordabcd.isSelected()){totalCharacters += lowercaseLetters;}
    if(password0123.isSelected()){totalCharacters += numbers;}
    if(passwordSymbols.isSelected()){totalCharacters += characters;}

    char[] text = new char[length];

    for(int i = 0; i < length; i++){text[i] = totalCharacters.charAt(rand.nextInt(length));}

    for (char c : text) { generatedString.append(c); }

    return generatedString.toString();
}

并在用户单击“生成”时设置此字符串的EditText。

GenerateDialog(@NonNull Context context) {
    super(context, android.R.style.Theme_NoTitleBar_Fullscreen);
    setContentView(R.layout.dialog_layout);

    ...

    generatePassword.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            passwordEditText.setText(generatedPassword());
        }
    });

    ...
}

但是很遗憾,passwordEditText“编辑文本”字段中看不到任何内容。

2 个答案:

答案 0 :(得分:2)

请尝试在按钮上使用isChecked()方法,而不要使用isSelected()

此外,您可能还想通过删除不必要的char[]数组来简化代码,而是这样做:

for (int i = 0; i < length; i++) {
   generatedString.append(totalCharacters.charAt(rand.nextInt(totalCharacters.length()));
}

答案 1 :(得分:1)

输入元素可能无法传达人们的想法,因此请确保控制参数lengthtotalCharacter正常。 {strong> @AGDownie 已经提到isChecked

private static final String numbers = "0918273645";
...

String totalCharacters = "";
if (passwordABCD.isSelected()) {totalCharacters += capitalLetters;}
if (passwordabcd.isSelected()) {totalCharacters += lowercaseLetters;}
if (password0123.isSelected()) {totalCharacters += numbers;}
if (passwordSymbols.isSelected()) {totalCharacters += characters;}
if (totalCharacters.isEmpty()) {
    throw new IllegalArgumentException("At least one kind of symbols required.");
}
if (length == 0) {
    throw new IllegalArgumentException("Empty password not allowed.");
}

char[] text = new char[length];
for (int i = 0; i < length; i++) {
    text[i] = totalCharacters.charAt(rand.nextInt(totalCharacters.length()));
}
return new String(text);