Java加密凯撒代码

时间:2014-03-30 21:18:51

标签: java

我是java的新手,在使用字符串和字符赋值时遇到问题 他们交织在一起。这里的Caesar程序没有运行,因为它之间的分配 必须比较字符和字符串。请帮忙 谢谢。

class Caesar {
    public static char encrypt(String str) {
        String result = "";
        String x;
        for (String ch : str) {
            x = plainalphabet.indexOf(ch);
            if (x != -1) {
                result = result + cipheralphabet.charAt(x);
            }
            else {
                result = result + ch;
            }
        }
        return result;
    }

    public static void main(String args[]) {
        String plainalphabet  = "abcdefghijklmnopqrstuvwxyz";
        String cipheralphabet = "defghijklmnopqrstuvwxyzabc";
        System.out.println(encrypt("James"));
    }
}

2 个答案:

答案 0 :(得分:1)

可能的解决方法:

public class Caesar {
    private static final String PLAIN = "abcdefghijklmnopqrstuvwxyz"; // fix scope

    private static final String CIPHER = "defghijklmnopqrstuvwxyzabc"; // fix scope

    public static String encrypt(String str)
    {
        String result = "";
        int x; // indexOf returns int
        for (final char ch : str.toCharArray()) { // str is not an Iterable
            x = PLAIN.indexOf(ch);
            if (x != -1) {
                result = result + CIPHER.charAt(x);
            } else {
                result = result + ch;
            }
        }
        return result;
    }

    public static void main(String args[])
    {
        System.out.println(encrypt("James"));
    }
}

(社区wiki,因为它几乎没有答案,几乎没有问题)

答案 1 :(得分:0)

首先,签名应更改为

public static String encrypt(String str)

而不是(String ch:str)使用

for (int i = 0; i < str.length(); i++)
相关问题