2 回答
TA贡献1891条经验 获得超3个赞
使用索引变量 for encryptedMessageArray,每次将字符放入时增加它encryptedMessageArray
int index = 0;
for (int i = 0; i < messageArray.length; i++) {
//System.out.println(messageArray[i]);
for (int k = 0; k < alphaArray.length; k++) {
if (messageArray[i] == alphaArray[k]) {
plainLetterIndex = k;
encryptedIndex = (char)(plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
encryptedMessageArray[index] = encryptedChar;
index++;
}
}
}
System.out.println();
System.out.println(encryptedMessageArray);
TA贡献1876条经验 获得超5个赞
将加密的字符或原始字符添加到您的,encryptedMessageArray以便您可以解密数组端获取原始消息
for (int i = 0; i < messageArray.length; i++) {
boolean isCharEncrypted = false;
for (int k = 0; k < alphaArray.length; k++) {
if (messageArray[i] == alphaArray[k]) {
plainLetterIndex = k;
encryptedIndex = (char)(plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
encryptedMessageArray[i] = encryptedChar;
isCharEncrypted = true;
}
}
if (!isCharEncrypted) {
encryptedMessageArray[i] = messageArray[i];
}
}
这是避免内部 for 循环的替代解决方案
for (int i = 0; i < messageArray.length; i++) {
char c = messageArray[i];
if (c >= 'A' && c <= 'Z') {
plainLetterIndex = c - 65; //A is ASCII 65
encryptedIndex = (char) (plainLetterIndex + encryptKey) % 26;
encryptedChar = alphaArray[encryptedIndex];
encryptedMessageArray[i] = encryptedChar;
} else {
encryptedMessageArray[i] = messageArray[i];
}
}
添加回答
举报