I have a textfield which takes long value and if it takes characters then it should display an error message. Is there any method like isNAN() for long to check whether that variable contains any character?
Asked
Active
Viewed 1,798 times
-1
-
4[What have you tried?](http://whathaveyoutried.com) There are many possible solutions. – jlordo Jan 23 '13 at 10:36
-
2possible duplicate of [Restricting JTextField input to Integers](http://stackoverflow.com/questions/11093326/restricting-jtextfield-input-to-integers) – assylias Jan 23 '13 at 10:37
-
I tried using try/catch. but is there any method like isNAN() to check whether the variable is a number or not – justified Jan 23 '13 at 10:41
-
@justified : care to accept any of the answer? – Priyank Doshi Jan 23 '13 at 12:22
5 Answers
1
The static method Long.parseLong()
will throw a NumberFormatException
if the string does not contain a parsable long.

Werner Kvalem Vesterås
- 10,226
- 5
- 43
- 50
-
1Or even better, prevent the user from entering a non number character with a filter. – assylias Jan 23 '13 at 10:37
-
1@justified.. Then catch the exception, and print the message from the properties file there. – Rohit Jain Jan 23 '13 at 10:39
1
You can usually do this by trying to do Long.parseLong(textfield.getText())
wrapped by a try
catch
block where you would catch the NumberFormatException
.
If the exception is caught then it means the user didn't enter a valid long
value.

Dan D.
- 32,246
- 5
- 63
- 79
1
long x = Long.parseLong("12345L");
You should try catch the above statement as it can throw NumberFormatException

Xavier DSouza
- 2,861
- 7
- 29
- 40
1
You can have a small utility method like this:
private boolean isLong(String str){
try{
Long.parseLong(str);
}
catch(NumberFormatException nfe){
return false;
}
return true;
}

Priyank Doshi
- 12,895
- 18
- 59
- 82
0
Just as an alternative to other solutions, you can use a regex
boolean containsCharacters = !txt.matches("-?\\d+");

Evgeniy Dorofeev
- 133,369
- 30
- 199
- 275