Do I need to use regular expression? But the digit of the input is unknown. Or there is a function in Java that does this?
Asked
Active
Viewed 1,223 times
0
-
1What do you mean by *valid number*? – Pshemo Nov 25 '13 at 20:12
-
Ivaylo Strandjev, That is exactly what I was trying to do but the parseInt does not give a feedback when it fails. What I want is a signal so that I can prompt the user to redo the input. – jsh6303 Nov 25 '13 at 20:31
-
Any combination of numbers 0-9. – jsh6303 Nov 25 '13 at 20:32
1 Answers
2
For instance if you want to check if a String
is a valid integer you can use Integer.parseInt. In case the String
does not store a number in valid format you will get a NumberFormatException so you can surround this code with a try/catch block.

Ivaylo Strandjev
- 69,226
- 18
- 123
- 176
-
Exceptions generally shouldn't be used for control flow. If you're running through this often and are just branching based on the numericalness of a number, then you shouldn't use an exception. – Cruncher Nov 25 '13 at 20:17
-
@Cruncher in this case writing a regex to check if the value is a valid integer(i.e. a 32 bit signed value) is very complex and the code readability and maintainability will suffer greatly from that. In fact I remember going into the same argument a few years ago with precisely your point, but in the end I gave up that there may be no better way to handle this situation. – Ivaylo Strandjev Nov 25 '13 at 20:21
-
Frankly there's no reason why this shouldn't be part of std lib if java wants to promote "ask permission" instead of "beg forgiveness". – Cruncher Nov 25 '13 at 20:28
-
That is exactly what I was trying to do but the parseInt does not give a feedback when it fails. What I want is a signal so that I can prompt the user to redo the input. – jsh6303 Nov 25 '13 at 20:30
-
1@JiajuShen What do you mean it doesn't give feedback when it fails?!?!? It jumps into the catch block instead of continueing in the try block. How is that not feedback? – Cruncher Nov 25 '13 at 20:33
-