【发布时间】:2017-10-02 16:39:54
【问题描述】:
目前,我正在编写一个程序,该程序使用 Java 在给定的字符串上执行 ROT-1 直到并包括 ROT-25。在我研究之初,我发现this代码:
public class Rot13 {
public static void main(String[] args) {
String s = args[0];
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 'a' && c <= 'm') c += 13;
else if (c >= 'A' && c <= 'M') c += 13;
else if (c >= 'n' && c <= 'z') c -= 13;
else if (c >= 'N' && c <= 'Z') c -= 13;
StdOut.print(c);
}
StdOut.println();
}
}
经过一些故障排除后,我得到了这个:
private static void rotALL(String input) {
//Loop 25 times, starting with ROT-1 and ending at ROT-25 (every possibliity besides the original input)
for (int i = 1; i < 26; i++) {
int rot = 26 - i;
System.out.print("ROT" + rot + ": ");
for (int charIndex = 0; charIndex < input.length(); charIndex++) {
char c = input.charAt(charIndex);
int inta = 97; //a in the ASCII table
int intaWithRot = inta + rot;
int intA = 65; //A in the ASCII table
int intAWithRot = intA + rot;
int intaWithRotPlusOne = intaWithRot + 1;
int intaWithRotPlusi = intaWithRot + i;
int intAWithRotPlusOne = intAWithRot + 1;
int intAWithRotPlusi = intAWithRot + i;
if (c >= inta && c <= intaWithRot) {
c += rot;
} else if (c >= intA && c <= intAWithRot) {
c += rot;
} else if (c >= intaWithRotPlusOne && c <= intaWithRotPlusi) {
c -= rot;
} else if (c >= intAWithRotPlusOne && c <= intAWithRotPlusi) {
c -= rot;
}
System.out.print(c);
}
System.out.println();
}
现在我要解决问题了:
当我使用 ROT-13 输入“grfg qngn”,即“测试数据”时,ROT-13 的输出是“ROT13: test d{t{”、“{”和“a "在ASCII表中相距26位,但我不知道为什么会出现这个错误,当“e”等字母正确显示时。
如何更改此算法,使其通过 ROT-1 到 ROT-25 循环?我认为这应该可以解决问题,但我错过了一些东西。
提前致谢和亲切的问候!
【问题讨论】:
-
原代码有什么问题?
-
它只适用于 ROT-13,而我想从 ROT-1 循环到 ROT-25。
-
好的,我想你会发现模数运算符“%”会让你的事情变得更容易。
-
我以前使用过模运算符,但我不知道如何在这个函数中有效地使用它。你能再解释一下吗?
标签: java encryption decode substitution