如何将ascii值转换回String? [重复]

时间:2022-10-30 15:55:18

This question already has an answer here:

这个问题在这里已有答案:

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?

我试图将String转换为ascii,更改ascii值,然后将这些值转换回字符串。我虽然在正确的轨道上,但我收到一条错误消息告诉我必须返回一个字符串;我哪里做错了?

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

}

1 个解决方案

#1


-1  

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

你的rot31方法必须返回一个String。您的代码有一个不会返回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:

如果找不到正确的值,您可以简单地返回一个空字符串,或者您可以选择返回null,或者抛出异常。一个例子如下所示:

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

}

#1


-1  

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

你的rot31方法必须返回一个String。您的代码有一个不会返回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:

如果找不到正确的值,您可以简单地返回一个空字符串,或者您可以选择返回null,或者抛出异常。一个例子如下所示:

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

}