Home > Software design >  In java How do I check that the first value of a input is a number?
In java How do I check that the first value of a input is a number?

Time:12-08

i need to ask the user for a number with letters, but the first value must be a number, how do I return true for that?

if(SerieNumber.charAt(0) == )

I don't know what to add there

CodePudding user response:

tl;dr

Character.isDigit( myString.codePointAt( 0 ) ) 

Avoid char

The char type has been legacy since Java 2. As a 16-bit value, char is physically incapable of representing most characters.

Code points

Instead use code point integer numbers.

int codePoint = myString.codePointAt( 0 ) ;  // Annoying zero-based index counting. So zero for first character. 

Test if that code point is assigned to a character that is considered to be a digit according to the Unicode Consortium.

boolean isDigit = Character.isDigit( codePoint ) ;

CodePudding user response:

Use regex:

if (SerieNumber.matches("\\d.*")) {
    // first char is a digit
}

If you need to allow digits from any language, add the unicode flag:

if (SerieNumber.matches("(?U)\\d.*")) {
    // first char is a digit from any character set, eg 9, 九, 구, etc
}
  • Related