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

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

    It partly depend on what you mean by "can be converted to an integer".

    If you mean "can be converted into an int in Java" then the answer from Jonas is a good start, but doesn't quite finish the job. It would pass 999999999999999999999999999999 for example. I would add the normal try/catch call from your own question at the end of the method.

    The character-by-character checks will efficiently reject "not an integer at all" cases, leaving "it's an integer but Java can't handle it" cases to be caught by the slower exception route. You could do this bit by hand too, but it would be a lot more complicated.

提交回复
热议问题