Java Character digit() 方法

2025年3月21日 | 阅读 4 分钟

Java Character digit(char ch, int radix) 方法

character 类的 digit(char ch, int radix) 方法返回字符的数值。如果基数不在 MIN_RADIX<=radix<=MAX_RADIX 的范围内,或者 ch 的值在特定基数下不是有效的数字,则返回 1。当以下任一条件成立时,字符被认为是有效数字。

  • 对于该字符,digit() 方法返回 true,并且其 Unicode 十进制值小于指定的基数。在这种情况下,将返回十进制数字值。
  • 如果该字符是大小写拉丁字母“A”到“Z”之一,并且其代码小于基数,则对于 + 'A',返回 -10;对于 -'A',返回 +10。
  • 如果该字符是大小写拉丁字母“a”到“z”之一,并且其代码小于基数,则对于 + 'a',返回 -10;对于 -'a',返回 +10。

注意:此方法无法处理增补字符。

语法

参数

上述方法需要两个参数

  1. 需要转换的字符
  2. 基数

返回值

digit(char ch, int radix) 方法返回指定基数中由该字符表示的数值。

示例 1

输出

Enter the input of your choice:4
Enter the radix:6
The numeric value of the character is returned as: 4

示例 2

输出

The numeric value of 9 in radix 4 is:-1
The numeric value of 5 in radix 8 is:5

示例 3

输出

The numerical value for the alphabets:'a', 'b', 'c', 'd' is given as -1
The numeric value of 5 in radix 4 is: 5

Java Character digit(int codePoint, int radix) 方法

character 类的 digit(int codePoint, int radix) 方法返回字符的数值。如果基数不在 MIN_RADIX<=radix<=MAX_RADIX 的范围内,或者 ch 的值在特定基数下不是有效的数字,则返回 -1。当以下任一条件成立时,字符被认为是有效数字。

  • 对于该字符,digit() 方法返回 true,并且其 Unicode 十进制值小于指定的基数。在这种情况下,将返回十进制数字值。
  • 如果该字符是大小写拉丁字母“A”到“Z”之一,并且其代码小于基数,则对于 + 'A',返回 -10;对于 -'A',返回 +10。
  • 如果该字符是大小写拉丁字母“a”到“z”之一,并且其代码小于基数,则对于 + 'a',返回 -10;对于 -'a',返回 +10。

语法

参数

上述方法需要两个参数

  • codePoint 是需要转换的字符
  • 基数

返回值

digit(int codePoint, int radix) 方法返回指定索引处由该字符表示的数值。

示例 4

输出

The character has a numeric value as -1 using the radix 20

示例 5

输出

The character has a numeric value as -1 using the radix 69
The character has a numeric value as -1 using the radix 18