roydbt roydbt - 2 years ago 173
Java Question

Java - String to number

For example,

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

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 Source

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

public static int convert(String str) {
        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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download