我正在做一个项目来加密和解密一个字符串。我已经成功为项目创建了一个加密和解密函数。我在使用另一个提示解决代码的函数时遇到了问题。这就是加密功能。
public static StringBuilder encryption(String word, int shiftValue) {
word = word.toUpperCase();
StringBuilder newWord = new StringBuilder(word);
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == ' ') {
i++;
}
while (shiftValue > 26) {
shiftValue = shiftValue - 26;
}
newWord.setCharAt(i, (char) (word.charAt(i) + shiftValue));
if (newWord.charAt(i) > 90 || newWord.charAt(i) < 65) {
while (newWord.charAt(i) > 90 || newWord.charAt(i) < 65) {
newWord.setCharAt(i, (char) (word.charAt(i) - 26 + shiftValue));
}
}
}
return newWord;
}
这是我解代码的代码
public static StringBuilder solve(String word, int maxShiftValue) {
word = word.toUpperCase();
int iterationCounter = 26;
StringBuilder newWord = new StringBuilder(word);
for (int i = 0; i < maxShiftValue; i++) {
newWord = encryption(word, 1);
System.out.println("Caesar " + iterationCounter + ": " + newWord);
iterationCounter--;
}
return newWord;
}
solve 方法的目标是将字符串中的字符更新一个字母,并打印出每个新字符串,直到字符串与原来的字符串相同。我遇到的问题是它只更新一次迭代的词。我不确定为什么并且对编码还很陌生。
主要方法
public static void main(String[] args) {
String word = "ab cd";
word = String.valueOf(encryption(word, 3));
System.out.println("word encrypted is " + word);
solve(word, 26);
}
输出