解密代码未更改实际数据



我遇到了正确运行代码的问题。我创建了一种解密方法,该方法应该说一个字并彼此替换每2个字母。除非这个词是奇怪的,否则我应该独自一人留下最后一封信。问题是我只在打印字母而不更改字符串的实际数据。

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

我知道您正在尝试修改字符串以解密它。好吧,我为您收到了一些新闻:Java中的String类是以这种方式的String对象不可变的方式设计的。这意味着一旦创建了它们的内容,就无法更改它们的内容。但是不用担心,还有其他方法可以实现自己的想法。

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

或多或少类似:

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

希望这对您有帮助。

字符串是不可变的,因此在字符串上调用方法不会更改字符串。它将仅返回从字符串派生的值。您需要制作一个新的空字符串并开始按字符添加返回值。

最新更新