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