从 Java 中的嵌套 for 循环中获取 passwords/characters 的列表

Get a list of passwords/characters from nested for-loops in Java

我了解嵌套 for 循环的工作原理,但我还不了解如何在 Java 中实现它们。在我的代码中,一定有错位的大括号,或者不合适的命令。我已经尝试了几个小时使用不同的配置无济于事。

我查看了有关 SO 的其他示例,包括其他编程语言中的一些示例。

我试图在文本框中获取的输出看起来像这样,

ekdk15hY7S

8fk4Wma7Ht

5kkr278nhS

等等

但我得到的只是文本框中的一行,而不是我想要的列表。我通过 GUI 告诉程序我想要多少个密码以及每个密码有多少 characters/digits。

当我注释掉第一个 for 循环并添加或删除大括号时,该代码可以很好地为我提供一个密码。

谁能看出我做错了什么?这是代码:

//  numb is how many characters per password.
String numbSTR = spinner1.getValue().toString();
int numb = Integer.parseInt(numbSTR);               

//count is how many passwords do you want.
String countSTR = spinner2.getValue().toString();
int count = Integer.parseInt(countSTR);


//count is how many passwords do you want.
for (int x = 0; x < count; x++ ) {
    String buildPW = "";
    //numb is how many characters per password.               
    for (int y = 0; y < numb; y++ ) {
        Random position = new SecureRandom();
        String digits =  "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";                                                                         
        int index = (int)     (position.nextDouble()*digits.length());
        buildPW += digits.substring(index, index+1);      
    }       

    TextArea1.setText(buildPW + crlf); // put each new password in the textbox.
}       

将 settext 和 buildPW 移到循环之外:

// Moved
String buildPW = "";
//count is how many passwords do you want.
for (int x = 0; x < count; x++ ) {
    //numb is how many characters per password.               
    for (int y = 0; y < numb; y++ ) {
        Random position = new SecureRandom();
        String digits =  "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";                                                                         
        int index = (int)     (position.nextDouble()*digits.length());
        buildPW += digits.substring(index, index+1) + crlf;      
    }
} 
// Moved
TextArea1.setText(buildPW); // put each new password in the textbox.

您的代码运行良好。这是大致相同的版本,有效:

public class HelloWorld {
  public static void main(String[] args) {

     int count = 10;
     int numb = 8;
     for (int x = 0; x < count; x++ ) {
     String buildPW = "";
     for (int y = 0; y < numb; y++ ) {

        String digits =      "0123456789abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";                                                                         
        int index = (int)     (Math.random()*digits.length());
        buildPW += digits.substring(index, index+1);
      }     

   System.out.println(buildPW);
   }  


  }
}

那么,您真正的问题是您在 textView 上设置了 Text。但您真正想要的是附加文本。所以,如果你改变:

 TextArea1.setText(buildPW + crlf);

 TextArea1.appendText(buildPW + crlf);

应该可以。

SetText,一次替换textArea中的全部文本。在您的情况下,您将 textArea 的内容设置为最新的最大密码。另一方面,appendText 将给定的文本附加到 textArea 中文本的末尾。 (类似于上面示例中的 System.out.println 代码)。