0

我正在编写一个具有多种编码方案的程序,其中一个是质数移位,基于键是偶数还是奇数。解码方案如下::

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);
}
4

2 回答 2

1

您的问题是,当它是偶数键和奇数字符串时,编码字符串的第一个“序列”中还会有一个字符,而您不考虑这一点:

如果密钥为 28,则新字符串应为“acegbdf”

上面的示例首先有 4 个字符,然后是最后 3 个字符。

在您的代码中,您正在运行(a.length()/2)上述字符串中的 3,这意味着您使用索引 0、1 和 2。当您真正想要的是使用 0、1、2 和 3 时(“aceg ”)。

解决方案是在您的 for 循环中为偶数键添加 1...这也将解决您未能告诉我们的 OUTOFBOUNDSEXCEPTION!

只是一个警告:我相信我的“解决方案”会导致你的偶数字符串失败,但做你的作业不是我的工作。:)

于 2013-08-08T12:18:58.003 回答
1

单步执行您的代码,甚至手动执行一些简单的示例:

  • 键:2;字符串:“A”

  • 键:2;字符串:“AB”

  • 键:2;字符串:“ABC”

  • 等等

详细检查会发生什么。当您知道发生了什么时,您就可以纠正问题。

于 2013-08-08T12:09:50.500 回答