[英]how to create an Encoder and Decoder for the Alphabetic substitution cipher (groovy)?
[英]substitution cipher technique where every letter is replaced with one 7 letters down the alphabetic line
我正在使用替换密码技术,其中每个字母都用字母线下的一个7个字母替换。如果输入的字之间出现空格,它也必须出现在输出中。
class Cipher
{
public static StringBuffer encrypt(String text, int s)
{
StringBuffer result= new StringBuffer();
for (int i=0; i<text.length(); i++)
{
if (Character.isUpperCase(text.charAt(i)))
{
char ch = (char)(((int)text.charAt(i)+s));
result.append(ch);
}
else
{
char ch = (char)(((int)text.charAt(i)+s));
result.append(ch);
}
}
return result;
}
public static void main(String[] args)
{
String text = "zhcl dhaly";
int s = -7;
System.out.println("Text : " + text);
System.out.println("Cipher: " + encrypt(text, s));
}
}
它显示正确的输出为harini.But如果我给“Zhcldhaly”它打印“sa \\ e] aZer”。但正确的输出是“Savewater”。
尝试使用模数来包裹任何字符,当移位时,将超过字母z
:
StringBuilder result = new StringBuilder();
int s = 7;
String text = "Zhcldhaly";
for (int i=0; i < text.length(); i++) {
char chr = text.charAt(i);
if (chr == ' ') {
result.append(" ");
}
else if (Character.isUpperCase(chr)) {
char ch = (char)('A' + (chr - 'A' - s + 26) % 26);
result.append(ch);
}
else {
char ch = (char)('a' + (chr - 'a' - s + 26) % 26);
result.append(ch);
}
}
System.out.println(result);
这输出:
Savewater
我假设你在抱怨sa\\e]aZer
,或者说准确:那里没有空间,这不是你的任务摇摆不定的。
事情是:
if (Character.isUpperCase(text.charAt(i)))
只检查char是否为大写。 它不检查char是否是空格。
这很简单:你需要一个if语句, if space, then append space else "translate"
。
另请注意:当前代码中的if语句毫无意义。 仔细查看“then”和“else”情况时,您会发现它们是相同的 。
所以,长话短说:仔细看看你需要什么样的if语句,并相应地改变你的代码。 仔细研究ASCII表以更好地理解输入字符的输出类型可能也非常有用。
除此之外:你应该明白解密和加密之间存在差异! 当您尝试取回原始文本时,您必须撤消操作! 当你减去7加密时,你需要添加 7来解密。 您无法使用加密方法解密加密的单词!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.