由k移位数组

时间:2011-09-05 12:58:46

标签: java

我正在研究一个小的java程序,它非常基本,我的一个函数用给定的键移动字母表。我已经有了它的工作,但它的方向是错误的,我怎么能让它转向另一个方向?

public static char[] ourAlphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};


    public  char[] shiftAlphabet(int key) {

            int length = ourAlphabet.length;

            char[] result = new char[length];

            for (int i=0; i < length; i++)
            {
                result[(i+key+26)%length] = ourAlphabet[i];
            }

            return result;
    }

我猜它很简单,但它让我很困惑!

例如;  用钥匙19产生; hijklmnopqrstuvwxyzabcdefg

什么时候应该生产; TUVWXYZABCDEFGHIJKLMNOPQRS

3 个答案:

答案 0 :(得分:8)

更改为:

result[i] = ourAlphabet[(i+key)%length];

答案 1 :(得分:2)

如果您使用result[(i-key+26)%length] = ourAlphabet[i];

,它应该有效

但是,如果长度!= 26,这仍然会给出错误的结果。

因此我会用长度替换26;

result[(i-key+length)%length] = ourAlphabet[i];

答案 2 :(得分:0)

public static char[] ourAlphabet = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};


public  char[] shiftAlphabet(int key) {

        int length = ourAlphabet.length;

        char[] result = new char[length];

        for (int i=0; i < length; i++)
        {
            ourAlphabet[(i+key+26)%length] = result[i];
        }

        return result;
}