java Character.getNumericValue() 问题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2148096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 19:41:34  来源:igfitidea点击:

Character.getNumericValue() issue

javacharcharacter

提问by folone

I'm probably missing something, but why are the two numeric values equal to -1?

我可能遗漏了一些东西,但为什么这两个数值等于-1

System.out.println(Character.getNumericValue(Character.MAX_VALUE));
System.out.println(Character.getNumericValue(Character.MIN_VALUE));

Returns:

返回:

-1
-1

回答by Michael Borgwardt

getNumericValue()will convert characters that actually represent numbers (like the "normal" digits 0-9, but also numerals in other scripts) to their numeric value. The Characters represented by Character.MAX_VALUEand Character.MIN_VALUEdo not have such a numeric value; they are not numerals. And according to the API doc:

getNumericValue()将实际表示数字的字符(如“普通”数字 0-9,以及其他脚本中的数字)转换为它们的数值。由Character.MAX_VALUE和表示的字符Character.MIN_VALUE没有这样的数值;它们不是数字。根据API 文档

If the character does not have a numeric value, then -1 is returned.

如果字符没有数字值,则返回 -1。

回答by Alan Moore

getNumericValue()only applies to characters that represent numbers, such as the digits '0'through '9'. As a convenience, it also treats the ASCII letters as if they were digits in a base-36 number system (so 'A'is 10 and 'Z'is 35).

getNumericValue()仅适用于表示数字的字符,例如数字'0''9'. 为方便起见,它还将 ASCII 字母视为 base-36 数字系统中的数字('A'10 和'Z'35 也是如此)。

This one fools a lot of people. If you want to know the Unicodevalue of a character, all you have to do is cast it to int:

这个骗了很多人。如果你想知道一个字符的Unicode值,你所要做的就是将它转换为int

System.out.println((int)Character.MAX_VALUE);
System.out.println((int)Character.MIN_VALUE);

回答by Kaleb Brasee

Because Character.MAX_VALUEand Character.MIN_VALUEaren't numeric. Character.getNumericValue(char)returns -1 when the parameter isn't a character that maps to a number.

因为Character.MAX_VALUECharacter.MIN_VALUE不是数字。 当参数不是映射到数字的字符时,Character.getNumericValue(char)返回 -1。

Number characters (0-9), letter characters (A-Z), and other unicode number characters are associated with values. I don't know all the other characters that are mapped. But many characters will just return -1.

数字字符 (0-9)、字母字符 (AZ) 和其他 unicode 数字字符与值相关联。我不知道映射的所有其他字符。但是很多字符只会返回-1。

回答by Andreas Dolk

.. just because \u0000and '\uffff` don't represent a digit and don't have a numeric value.

.. 只是因为\u0000and '\uffff` 不代表数字并且没有数值。

I guess you were looking for the 16bit value of the char, but for this we can simply cast:

我猜您正在寻找字符的 16 位值,但为此我们可以简单地转换:

int value = (int) Character.MAX_VALUE;