3

我正在尝试编写一个简单的加密算法,它是一种随机移位模式加密。我已经将它编写为基于所有字符的数组,然后使用 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);
    }
4

2 回答 2

5

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

//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);
}
于 2012-10-12T05:53:06.750 回答
1
String[] alphashuff = ...;
List list = Arrays.asList(alphashuff);
Collections.shuffle(list);

这个列表现在被打乱了,它由 alphashuff 的值组成。

并像这样使用 -output = output + list.get(n);

于 2012-10-12T05:57:01.897 回答