How would you check if a String was a number before parsing it?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Here are two methods that might work. (Without using Exceptions). Note : Java is a pass-by-value by default and a String's value is the address of the String's object data. So , when you are doing
You have changed the input value to have no spaces. You can remove that line if you want.
Here is another method in case you want to allow floats This method allegedly allows numbers in the form to pass 1,123,123,123,123,123.123 i have just made it , and i think it needs further testing to ensure it is working.
Do not use Exceptions to validate your values. Use Util libs instead like apache NumberUtils:
Edit:
Please notice that, if your string starts with an 0, NumberUtils will interpret your value as hexadecimal.
A well-performing approach avoiding try-catch and handling negative numbers and scientific notation.
You can use the java.util.Scanner object.
You can use NumberUtils.isCreatable() from Apache Commons Lang.
Since NumberUtils.isNumber will be deprecated in 4.0, so use NumberUtils.isCreatable() instead.