-1

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?

justified
  • 95
  • 1
  • 3
  • 12

5 Answers5

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
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