Search code examples
javastringdecodeencodedestroy

Java breaks string into rubbish at encoding/decoding


Hello I have a simple encoding/decoding method in java (running in eclipse) which returns the encoded or rather decoded string, chosen by parameter key (if key < 0 then execute decoding else encoding).

The method gets executed in void main like the following code shows.

public static void main(String[] args)
{
    System.out.println(rotate("programm", 42));
}

My encoding/decoding method looks like this:

public static String rotate(String text, int key)
{
    // Check if given key is in range -25 to 25
    if (key < -42 || key > 42)
        return "";

    if (key == 0)
        return text;

    char[] array = text.toCharArray();
    int k = key % 26;

    // Check if every char of given text is in rang from 'a' to 'z'
    // Use text as char array to manipulate each char
    for (int i = 0; i < array.length; ++i) {
        if (array[i] < 'a' || array[i] > 'z') {
            return "";
        }
        else {
            if (key < 0) {
                int j = (int)array[i] - k;
                if (j < 'a')
                    array[i] = (char)(j+26);
                else
                    array[i] -= k;
            }
            else {
                int j = (int)array[i] + k;
                if (j > 'z')
                    array[i] = (char)(j-26);
                else
                    array[i] += k;
            }
        }
    }       
    return array.toString();
}

The problem is that the result array of rotate(..) is equals to "fhewhqcc" which is right but the console prints "[C@123a439b".

Do you have any idea?


Solution

  • You are returning a Char Array and not a String. Hence the printed output is like that. You need to change the return statement as follows:

    return new String(array);