我正在编写一个具有多种编码方案的程序,其中一个是质数移位,基于键是偶数还是奇数。解码方案如下::
The key is checked to see whether it is odd or even. For an odd key, odd numbered characters are in order first in the new string, then all even indexes. If the key is even all even indexes are first, then all the odd indexes
因此,对于字符串“abcdefg”和 27 的键,如果键为 28,新字符串应为“bdfaceg”,则新字符串应为“acegbdf”
奇怪的是,如果密钥是奇数,并且字符串长度是奇数或偶数,它会完美解码。如果键是偶数并且字符串长度是偶数,它将很好地解码,
但是,如果键是偶数并且字符串长度是奇数,它将无法正确解码。
使用测试字符串“在此处输入消息”。这些是我的输出::
Encoded Key = 28 ; Encoded Message "EtrMsaehr.ne esg ee" Message length = 19
Decoded Key = 28 ; Decoded Message "E.tnreM seasegh renull"
所以偶数条目在正确的位置,但奇数条目要么需要被反向拉动,要么需要被奇数索引推回,我认为......我认为将它们推回索引是最简单的,但我仍然相当Java新手,我不知道该怎么做。
这是我在这个实例中使用的函数的代码。
protected String decode(String a, int k)
{
System.out.println(a.length());
String[] out = new String [a.length()];
String decode = a;
int key = k;
boolean kP = IsEven(key);
String odd = "";
if (kP)
{
//Key is even
try
{
int f = 0;
for (int i =0 ; i<(a.length()/2); i++)
{
out[f] = Character.toString(a.charAt(i));
f+=2;
}
int g = 1;
for (int i = (a.length()/2) ; i<(a.length()); i++)
{
out[g] = Character.toString(a.charAt(i));
g+=2;
}
}
catch ( IndexOutOfBoundsException e )
{
System.out.println("Out of bounds");
while(true)
break;
}
}
else
{
//key is odd
try
{
int f = 1;
for (int i =0 ; i<(a.length()/2); i++)
{
out[f] = Character.toString(a.charAt(i));
f+=2;
}
int g = 0;
for (int i = (a.length()/2) ; i<(a.length()); i++)
{
out[g] = Character.toString(a.charAt(i));
g+=2;
}
}
catch ( IndexOutOfBoundsException e )
{
System.out.println("Out of bounds");
while(true)
break;
}
}
for (int i = 0 ; i<a.length(); i++)
odd += out[i];
System.out.println(odd);
return(odd);
}