这种替换密码应该对字母表进行打乱,并通过在正常字母表中找到消息中字母的位置并将其替换为打乱字母表中相同位置的字母来对消息进行编码。
因此,像“ABC”这样的消息,使用“QWERTYUIOPASDFGHJKLZXCVBNM”这样的打乱字母表将变成“QWE”。
我的问题是标点符号和空格被其他字母替换,并且每个字母实际上并不对应于它的实际位置,它总是比它应该在的位置晚一个位置。第二部分有点令人费解,但不是大问题。
这是我的代码:
public static String cryptocodeM(String msg) {
String[] alphabetArray = {"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"};
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String newMsg = "";
List<String> list = Arrays.asList(alphabetArray);
Collections.shuffle(list);
StringBuffer alph2 = new StringBuffer();
for (int i = 1; i < list.size(); i++) {
alph2.append(list.get(i));
}
String scramb = alph2.toString(); //the scrambled alphabet
System.out.println(scramb);
msg = msg.toUpperCase();
for (int x = 0; x < msg.length(); x++) {
char a = msg.charAt(x); // the letters in msg
int index = alphabet.indexOf(a) + 1; // index of the letters in the alphabet //when I don't add 1 here I get a runtime error saying "String out of range -1"
char b = scramb.charAt(index); //finds letters in the same postion in the scrambled alphabet
newMsg += b; //Adds up the letters
}
return newMsg;
}
此时,我不知道如何解决这个问题,因为我刚刚开始学习字符串。如果您能提供帮助,我将非常感激。
最佳答案
index
为-1
表示搜索没有找到。请参阅:String.indexOf()
尝试这样的事情:
private static final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final char[] scramb = alphabet.toChararray();
public static String cryptocodeM(String msg)
{
if (null == msg || msg.isEmpty() )
return msg;
final StringBuilder newMsg = new StringBuilder(msg.length());
shuffleArray(scramb);
System.out.println(new String(scramb));
msg = msg.toUpperCase();
for (int x= 0; x < msg.length(); x++)
{
char a = msg.charAt(x);
final int index = alphabet.indexOf(a);
if (index > -1)
a = scramb[index];
newMsg.append(a);
}
return newMsg.toString();
}
public static void shuffleArray( char[] array )
{
final Random rnd = new Random();
for ( int i = array.length - 1 ; i > 0 ; --i )
{
final int index = rnd.nextInt( i + 1 );
// Simple swap
final char a = array[index];
array[index] = array[i];
array[i] = a;
}
}
已编辑
问题是,char[]
与 T...
,即基元数组与对象数组...所以我只是从所以,发现了这个:Random shuffling of an array
关于java - 在替换密码 Java 中保留空格和标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46657706/