當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。