How to check if a String is numeric in Java

前端 未结 30 2642
盖世英雄少女心
盖世英雄少女心 2020-11-21 05:26

How would you check if a String was a number before parsing it?

30条回答
  •  猫巷女王i
    2020-11-21 06:05

    That's why I like the Try* approach in .NET. In addition to the traditional Parse method that's like the Java one, you also have a TryParse method. I'm not good in Java syntax (out parameters?), so please treat the following as some kind of pseudo-code. It should make the concept clear though.

    boolean parseInteger(String s, out int number)
    {
        try {
            number = Integer.parseInt(myString);
            return true;
        } catch(NumberFormatException e) {
            return false;
        }
    }
    

    Usage:

    int num;
    if (parseInteger("23", out num)) {
        // Do something with num.
    }
    

提交回复
热议问题