Home > Software design >  What does Character.isDigit return?
What does Character.isDigit return?

Time:07-03

I found this example online. peek contains one character read from the buffered reader with readch(br). The following cycle must continue until the read character is a number

while(Character.isDigit(peek) 
    && !Character.isLetter(peek) && peek != '_') {
    int n = (int) peek - 48;
    sum = sum*10   n;
    readch(br);
}

Isn't it enough to just say Character.isDigit?

CodePudding user response:

Yes, it's redundant. Character.isDigit returns true if the character type (from Character.getType) is DECIMAL_DIGIT_NUMBER, and Character.isLetter returns true if the same type is one of several categories (DECIMAL_DIGIT_NUMBER is not one of the categories listed).

getType returns a single value, so there are no characters that have multiple types according to Java. Thus, there is no character for which isDigit and isLetter both return true. Likewise, _ is CONNECTOR_PUNCTUATION (easy to see this with a quick sample Java program), which is neither a digit nor a letter.

So this is code by someone who was being overly defensive. isDigit suffices.

CodePudding user response:

The sample is doing the job only halve.

It assumes that Character::isDigit returns true only for the characters '0' to '9', but that is wrong. This also means that the calculation (int) peek - 48 is not reliable to get the numeric value of the digit.

When the code should really work on any kind of digits, it needs to look like this:

final var radix = 10;
var value = 0;
while( Character.isDigit( peek) && ((value = Character.digit( peek, radix )) != -1) ) 
{
  sum = sum * radix   value;
  readch( br );
}

To cover also the hex digits from 'A' to 'F' or their lowercase equivalents, just remove the Character::isDigit check (and change radix accordingly).

Using Character::getNumericValue would also get the Roman numbers, but this will not work properly for the calculation of sum.

  •  Tags:  
  • java
  • Related