0

I am trying to convert String into ascii, alter the ascii value, and then convert those values back into a string. I though I was on the right track, but I am getting an error message telling me I must return a String; where did I go wrong?

public static boolean safeToUse(String text) {

    text = text.toUpperCase();

    int length = text.length(); 

    for ( int a=0; a < length; a++ ) { 

        char c = text.charAt(a); 

        if (c < FIRST || c > LAST) {  //checking range

            return false;
        }
    }
    return true;

}

public static String rot31(String message)
{
    message = message.toUpperCase();

    int length = message.length();  
    for ( int x=0; x < length; x++ ) { 

        int ch = message.charAt(x); 

        if (ch <= 62) {

            int ascii = ch + 31;
        } else {

            int ascii = ch - 62;

            String coded = Integer.toString(ascii);

            return coded;
        }
    }

}
Bruno Peres
  • 15,845
  • 5
  • 53
  • 89
soshelp
  • 9
  • 1
  • 1
    hint: what does `rot31(String)` return for an empty `String` as `""` ? Also i think you are missinterpresting what `return` does, as i don´t think you want to return on the first `char` occurence beeing greater than `62` – SomeJavaGuy Oct 04 '16 at 14:29
  • `rot31` may never return if no character in the string has an ASCII value higher than 62. I think the compiler is complaining about that. – Federico klez Culloca Oct 04 '16 at 14:33

1 Answers1

-1

Your rot31 method must return a String. Your code has a path where it will not return a String.

You can simply return an empty String if the proper value is not found, or you could choose to return a null, or throw an exception. An example is shown below:

public static String rot31(String message)
{
    message = message.toUpperCase();

    int length = message.length();
    for (int x = 0; x < length; x++)
    {

        int ch = message.charAt(x);

        if (ch <= 62)
        {
            int ascii = ch + 31;
        }
        else
        {

            int ascii = ch - 62;

            String coded = Integer.toString(ascii);

            return coded;
        }
    }

    // Failed to find the correct value
    return "";

}
starf
  • 1,063
  • 11
  • 15