roydbt roydbt - 7 months ago 26
Java Question

Java - String to number

For example,

"Hello"
will be turned to a number and
10
will be turned to 10. If I will try again
"Hello"
I will get the same number I got before.
How can I do that?

Edit:
I don't know what "Hello" be turned to, because I don't have a program which does what I want. I don't want a specific number to be displayed.

Answer

You could use String::hashCode for Strings, and first try to parse to an integer to get numbers:

public static int convert(String str) {
    try{
        return Integer.parseInt(str.trim());
    }catch(Exception e) {
        return str.hashCode();
    }
}

But if you have things like "10 10", you will still get the hash code and not just 1010

Comments