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

后端 未结 30 1896
野趣味
野趣味 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:22

    I believe there's zero risk running into an exception, because as you can see below you always safely parse int to String and not the other way around.

    So:

    1. You check if every slot of character in your string matches at least one of the characters {"0","1","2","3","4","5","6","7","8","9"}.

      if(aString.substring(j, j+1).equals(String.valueOf(i)))
      
    2. You sum all the times that you encountered in the slots the above characters.

      digits++;
      
    3. And finally you check if the times that you encountered integers as characters equals with the length of the given string.

      if(digits == aString.length())
      

    And in practice we have:

        String aString = "1234224245";
        int digits = 0;//count how many digits you encountered
        for(int j=0;j

    And the results are:

    It's an integer!!

    It's not an integer!!

    Similarly, you can validate if a String is a float or a double but in those cases you have to encounter only one . (dot) in the String and of course check if digits == (aString.length()-1)

    Again, there's zero risk running into a parsing exception here, but if you plan on parsing a string that it is known that contains a number (let's say int data type) you must first check if it fits in the data type. Otherwise you must cast it.

    I hope I helped

提交回复
热议问题