What's the best way to check if a String represents an integer in Java?

后端 未结 30 1495
野趣味
野趣味 2020-11-22 05:45

I normally use the following idiom to check if a String can be converted to an integer.

public boolean isInteger( String input ) {
    try {
        Integer.         


        
30条回答
  •  鱼传尺愫
    2020-11-22 06:32

    This is a Java 8 variation of Jonas Klemming answer:

    public static boolean isInteger(String str) {
        return str != null && str.length() > 0 &&
             IntStream.range(0, str.length()).allMatch(i -> i == 0 && (str.charAt(i) == '-' || str.charAt(i) == '+')
                      || Character.isDigit(str.charAt(i)));
    }
    

    Test code:

    public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        Arrays.asList("1231231", "-1232312312", "+12313123131", "qwqe123123211", "2", "0000000001111", "", "123-", "++123",
                "123-23", null, "+-123").forEach(s -> {
            System.out.printf("%15s %s%n", s, isInteger(s));
        });
    }
    

    Results of the test code:

            1231231 true
        -1232312312 true
       +12313123131 true
      qwqe123123211 false
                  2 true
      0000000001111 true
                    false
               123- false
              ++123 false
             123-23 false
               null false
              +-123 false
    

提交回复
热议问题