有没有一种方法可以更清晰地为凯撒密码编写Java代码?

时间:2019-07-17 12:36:05

标签: java

我刚刚开始学习编程,而Java是我的第一门语言。我为我在edX上上课的Caesar密码编写了代码。它可以按预期工作,但我想知道是否有更优雅的方式来编写此代码。在下面,我附上了我写的方法,这些方法对我来说似乎有点冗长,但是我不太确定。

// returns alphabet shifted by amount specified as key
// this code was provided by the class I'm taking
public static String shiftAlphabet(int shift) {
    int start = 0;

    if (shift < 0) {
        start = (int) 'Z' + shift + 1;
    } else {
        start = 'A' + shift;
    }

    String result = "";
    char currChar = (char) start;

    for(; currChar <= 'Z'; ++currChar) {
        result = result + currChar;
    }

    if(result.length() < 26) {
        for(currChar = 'A'; result.length() < 26; ++currChar) {
            result = result + currChar;
        }
    }

    return result;
}

// encrypts the text by using the previous shiftAlphabet() method
// key: amount to shift the alphabet by
public static String caesarify(String text, int key) {
    String normalAlphabet = shiftAlphabet(0);
    String shiftedAlphabet = shiftAlphabet(key);
    String caesarifiedText = "";

    for (int i = 0; i < text.length(); i++) {
        int temp = normalAlphabet.indexOf(text.charAt(i));
        caesarifiedText += shiftedAlphabet.charAt(temp);
    }

    return caesarifiedText; 
}

// splits the encrypted text into blocks
// n: length of block
// un-filled blocks are padded with x, e.g. HIGU YSxx
public static String groupify(String text, int n) {
    String temp = ""; 
    int sets = 0;

    for (; text.length() > 0; ) {
        temp += text.substring(0, 1);
        text = text.substring(1);
        if ((temp.length() - sets) % n == 0) {
            temp += " ";
            sets++;
        }
    }

    if (text.length() == 0) {
        int count = 0;
        for (int i = temp.lastIndexOf(" ") + 1; i < temp.length(); i ++) {
            ++ count;
        }

        for (int i = n - count; i > 0; i--) {
            temp += "x";
        }
    }

    return temp;
}

0 个答案:

没有答案