java - Collections.shuffle 没有按预期工作

标签 java arrays shuffle

我正在尝试编写一个简单的加密算法,它是一种随机移位模式加密。我将其编写为基于所有字符的数组,然后使用 Collections.shuffle 然后将其匹配。然而,由于输出文本与输入相同,因此数组似乎没有改组

这是我的方法

static void encrypt(String s)
    {
        //Define variable for indexOf output
        int n;

        //Encrypted output
        String output = "";

        //Shuffle array to create random replacements
        Collections.shuffle(Arrays.asList(alphashuff));

        //Create new string
        String alpha = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

        for (int index = 0; index < s.length();index++)
        {
            char aChar = s.charAt(index);
            n = alpha.indexOf(aChar, 0);

            if(n == -1)
            {
                output = output + aChar;
            }
            else
            {
                output = output + alphashuff[n];
            }

        }

        //Print encrypted string to console
        System.out.println("Encrypted Text: " + output);
    }

最佳答案

您不是在打乱数组,而是使用数组创建的列表。在将列表发送到随机播放之前创建列表:

//I'm assuming alphashuff is a char[]
List<Character> lstCh = new ArrayList<Character>();
for(char c : arrCh) {
    lstCh.add(c);
}
Collections.shuffle(lstCh);
//...
else
{
    output = output + lstCh.get(n);
}

关于java - Collections.shuffle 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12853022/

相关文章:

java - 如何从 xml 解析器获取值到其他类

c# - Array.sort 函数影响数组,我认为它不应该影响

c++ - random_shuffle 列表通过将它复制到一个 vector 然后返回

php - 如何通过提供种子并获得相同顺序来随机化 PHP 中的数组?

C++ vector 随机洗牌它的一部分

java - 如何使用 PowerMockito 在静态方法中模拟新类实例

java.sql.SQLException : The url cannot be null

Java实体交集

javascript - 如何检查一个数组中的某个项是否存在于另一个数组中?

ios - 使用嵌套快速枚举耗时过长,如何优化?