简体   繁体   English

Character.isDigit 返回什么?

[英]What does Character.isDigit return?

I found this example online.我在网上找到了这个例子。 peek contains one character read from the buffered reader with readch(br) . peek 包含使用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 ?仅仅说Character.isDigit还不够吗?

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).如果字符类型(来自Character.getType )是DECIMAL_DIGIT_NUMBER ,则Character.isDigit返回 true ,如果相同类型是多个类别之一( DECIMAL_DIGIT_NUMBER不是列出的类别之一),则Character.isLetter返回 true 。

getType returns a single value, so there are no characters that have multiple types according to Java. getType返回单个值,因此根据 Java 不存在具有多种类型的字符。 Thus, there is no character for which isDigit and isLetter both return true.因此,没有isDigitisLetter都返回 true 的字符。 Likewise, _ is CONNECTOR_PUNCTUATION (easy to see this with a quick sample Java program), which is neither a digit nor a letter.同样, _CONNECTOR_PUNCTUATION (通过快速示例 Java 程序很容易看到这一点),它既不是数字也不是字母。

So this is code by someone who was being overly defensive.所以这是一个过度防御的人的代码。 isDigit suffices. isDigit就足够了。

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.它假定Character::isDigit仅对字符 '0' 到 '9' 返回true ,但这是错误的。 This also means that the calculation (int) peek - 48 is not reliable to get the numeric value of the digit.这也意味着计算(int) peek - 48不能可靠地得到数字的数值。

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).要覆盖从 'A' 到 'F' 的十六进制数字或它们的小写等价物,只需删除Character::isDigit检查(并相应地更改radix )。

Using Character::getNumericValue would also get the Roman numbers, but this will not work properly for the calculation of sum .使用Character::getNumericValue也可以获得罗马数字,但这对于sum的计算将无法正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM