我正在尝试生成字母的随机密钥,该密钥在整个密钥中仅使用一次。我目前有一个数组“ regKey”,它以正常顺序存储字母A-Z。我想创建一个新数组“ newKey”,其中字母的顺序是完全随机的,但是在创建此新数组时将使用每个字母。新数组中不应有任何字母的重复项。

到目前为止,我已经能够生成随机密钥,但是通常某些字母重复。这是我的以下代码供参考。

public void keyGen() {
             char [] regKey = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
             char [] newKey = new char [26];

             int tempNum;
             int totalChoice = 26;

             Random rand = new Random();

             for(int i = 0; i<26; i++) {
                 tempNum = rand.nextInt(totalChoice);

                 newKey[i] = regKey[tempNum];

                 System.out.print(newKey[i]);
             }

             String keyString = new String (newKey);

             label_key.setText(keyString);
        }

最佳答案

假设您首先肯定需要一个Array,下面的代码将创建您想要的输出:

char [] regKey = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
char [] newKey = new char [26];
String[] array = new String(regKey).split("", 0);
ArrayList<String> yourNewArrayList = new ArrayList<String>();
Collections.addAll(yourNewArrayList, array);
Collections.shuffle(yourNewArrayList);
for (int i = 0; i < newKey.length; i++) {
    newKey[i] = yourNewArrayList.remove(0).toCharArray()[0];
}

关于java - 无法生成随机字母的 key ,该 key 只​​能在整个 key 中使用/找到一次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58916340/

10-11 19:53
查看更多