当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Character getNumericValue()用法及代码示例


字符类的 getNumericValue() 方法返回指定字符的 int 值。如果字符没有任何 int 值,则返回 -1。如果字符具有不能表示为非负整数的数值,则返回 -2。

用法

public static int getNumericValue(int codePoint)

参数

上述方法只需要一个参数:

codePoint 是要转换的字符(Unicode 代码点)。

返回值

getNumericValue(int codePoint) 方法返回字符的数值,作为一个非负的 int 值。如果字符具有数值但该值不能表示为非负 int 值,则此方法将返回 -2。如果字符没有数值,该方法将返回 -1。

例子1

public class JavaCharactergetNumericValueExample1 {
	public static void main(String[] args) {
		// Initialize a codepoint
		int codepoint = 110;
		// Convert codepoint to char
		char ch = (char) codepoint;
		// Convert the code point to its numeric value
		int digit = Character.getNumericValue(codepoint);
		// Print the result
System.err.println("The character '" + ch + "' has a numeric value represented as:" + digit);
	}
}

输出:

The character 'n' has a numeric value represented as:23

例子2

public class JavaCharactergetNumericValueExample2 {
   public static void main(String[] args) {
	 int obj1 = 88, obj2 = 0x0f600;
	 int a1 = Character.getNumericValue(obj1);
	 int b2 = Character.getNumericValue(obj2);
	 String str1 = "Numeric value for code point obj1 is " + a1;
	 String str2 = "Numeric value for code point obj2 is " + b2;
   // Print a1 and i2 
	 System.out.println( str1 );
	 System.out.println( str2 );
	   }
	}

输出:

Numeric value for code point obj1 is 33
Numeric value for code point obj2 is -1

例子3

public class JavaCharactergetNumericExample3 {
	   public static void main(String[] args) {
		// Initialize a codepoint
			int codepoint1 = 110;
		    int codepoint2 = 00;			
		    int codepoint3 = 54;
	   // Convert codepoint to char
		    char ch1 = (char) codepoint1;
			char ch2 = (char) codepoint2;
		    char ch3 = (char) codepoint3;
	   // Convert the code point to its numeric value
			int digit1 = Character.getNumericValue(codepoint1);
			int digit2 = Character.getNumericValue(codepoint2);
		    int digit3 = Character.getNumericValue(codepoint3);
	  // Print the result
	System.err.println("The character '" + ch1 + "' has a numeric value represented as:" + digit1);
	System.err.println("The character '" + ch2 + "' has a numeric value represented as:" + digit2);
	System.err.println("The character '" + ch3 + "' has a numeric value represented as:" + digit3);
				}
			}

输出:

The character 'n' has a numeric value represented as:23
The character ' ' has a numeric value represented as:-1
The character '6' has a numeric value represented as:6



相关用法


注:本文由纯净天空筛选整理自 Java Character getNumericValue() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。