解密代码不会改变实际数据

时间:2017-04-28 16:14:42

标签: java encryption

我在运行代码时遇到问题。我创建了一个解密方法,该方法应该采用一个单词并相互替换每两个字母。除非这个词是奇数,否则我应该留下最后一封信。问题是我只打印出字母而不是改变字符串的实际数据。

static String ezDecrypt (String ezEncrypt){

    //this variable holds the value of the String's length
    int cl = ezEncrypt() ;

    //if the length of the String is even then do this
    if (ezEncrypt.length() % 2 == 0){

        //for loop that begins at 0
        //keeps looping until it reaches the end of the string
        //each loop adds 2 to the loop
        for(int i = 0; i < cl; i= i + 2) {
            //will print out the second letter in the string
            System.out.print(ezEncrypt.charAt(i + 1));
            //will print out the first letter in the string 
            System.out.print(ezEncrypt.charAt(i));             
        }
    }
    //if the length of the word is an odd number, then 
    else if(ezEncrypt.length() % 2 != 0){
        //loop through and do the same process as above
        //except leave this loop will skip the last letter
        for(int i = 0; i < cl-1; i= i + 2) {
            //will print out the second letter in the string
            System.out.print(ezEncrypt.charAt(i + 1));
            //will print out the first letter in the string 
            System.out.print(ezEncrypt.charAt(i));  
        }
    }
    return ezEncrypt;

}

2 个答案:

答案 0 :(得分:2)

我知道您正在尝试修改字符串以解密它。好吧,我收到了一些消息:java中的String类以这样的方式设计String对象是不可变的。这意味着您在创建内容后无法更改其内容。但不要担心,还有其他方法可以实现您的想法。

例如,您可以通过调用ezEncrypt.toCharArray()从收到的对象中获取一组字符;你可以修改数组的内容,这样你就必须使用它,就像你应该的那样交换字符。然后,解密完成后,使用构造函数String创建另一个new String(char[] chars)对象,将数组作为参数传递,然后返回。

或多或少像这样:

static String ezDecrypt (String ezEncrypt){
    //this variable holds the value of the String's length
    int cl = ezEncrypt.length();

    //an array holding each character of the originally received text
    char[] chars = ezEncrypt.toCharArray();

    //temporary space for a lonely character
    char tempChar;

    //Do your swapping here
    if (ezEncrypt.length() % 2 == 0){ //Length is even
        //for loop that begins at 0
        //keeps looping until it reaches the end of the string
        //each loop adds 2 to the loop
        for(int i = 0; i < cl; i = i + 2) {
            tempChar = chars[i];
            chars[i] = chars[i+1];
            chars[i+1] = tempChar;
        }
    } else { //Length is odd
        //loop through and do the same process as above
        //except leave this loop will skip the last letter
        for(int i = 0; i < cl - 1; i = i + 2) {
            tempChar = chars[i];
            chars[i] = chars[i+1];
            chars[i+1] = tempChar;
        }
    }
    return new String(chars);
}

希望这会对你有所帮助。

答案 1 :(得分:1)

字符串是不可变的,因此调用字符串上的方法不会更改字符串。它只返回从字符串派生的值。您需要创建一个新的空字符串并开始逐个字符地添加返回值。