Best implementation for an isNumber(string) method

前端 未结 19 2542
感动是毒
感动是毒 2020-12-15 20:04

In my limited experience, I\'ve been on several projects that have had some sort of string utility class with methods to determine if a given string is a number. The idea h

19条回答
  •  粉色の甜心
    2020-12-15 20:31

    I needed to refactor code like yours to get rid of NumberFormatException. The refactored Code:

    public static Integer parseInteger(final String str) {
        if (str == null || str.isEmpty()) {
            return null;
        }
        final Scanner sc = new Scanner(str);
        return Integer.valueOf(sc.nextInt());
    }
    

    As a Java 1.4 guy, I didn't know about java.util.Scanner. I found this interesting article:

    http://rosettacode.org/wiki/Determine_if_a_string_is_numeric#Java

    I personaly liked the solution with the scanner, very compact and still readable.

提交回复
热议问题