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


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

字符类的 forDigit(int digit, int radix) 方法确定指定基数中特定数字的字符表示。如果数字的值不是指定基数中的有效数字,或者基数的值不是有效基数,则返回空字符。如果数字小于 10,则返回 '0'+数字。否则,返回值 'a'+digit-10。

用法

public static char forDigit(int digit, int radix)

参数

上述方法需要两个参数:

需要转换为字符的数字。

基数

返回值

forDigit(int digit, int radix) 方法返回指定索引中指定数字的字符表示。

例子1

public class JavaCharacterforDigitExample1 {
    public static void main(String[] args) {
     int a1 = 5;
     int a2 = 6;
       char ch1 = Character.forDigit(a1, 10);
    char ch2 = Character.forDigit(a2, 16);
String str1 = "The char representation of " + a1 + " in radix 10 is " + ch1; String str2 = "The char representation 
of " + a2 + " in radix 16 is " + ch2; System.out.println( str1);
System.out.println( str2 );
       }
    }

输出:

The char representation of 5 in radix 10 is 5
The char representation of 6 in radix 16 is 6

例子2

public class JavaCharacterforDigitExample2 {
    public static void main(String[] args) {
        int a1 = 5;
        int a2 = 15;
        int a3 = 27;
        char ch1 = Character.forDigit(a1, 10);
        char ch2 = Character.forDigit(a2, 16);
        char ch3 = Character.forDigit(a3, 34);
        String str1 = "The char representation of " + a1 + " in radix 10 is " + ch1;
        String str2 = "The char representation of " + a2 + " in radix 16 is " + ch2;
        String str3 = "The char representation of " + a3 + " in radix 16 is " + ch3;
        System.out.println( str1 );
        System.out.println( str2 );
        System.out.println( str3 );
     }
  }

输出:

The char representation of 5 in radix 10 is 5
The char representation of 15 in radix 16 is f
The char representation of 27 in radix 16 is r

例子3

import java.util.Scanner;
public class JavaCharacterforDigitExample3 {
     public static void main(String[] args) {
     // Ask the user for the input
        System.out.print("Enter an input:");
        Scanner s = new Scanner(System.in);
        int digit = s.nextInt();
      // Ask the user for the radix
        System.out.print("Enter the radix:");
         int radix = s.nextInt();
         char result = Character.forDigit(digit, radix);
  System.out.println("The character representation using radix \'" + radix + "\' for digit " + digit + "  is:" + result);
             }
    }

输出:

Enter an input:4
Enter the radix:7
The character representation using radix '7' for digit 4  is:4



相关用法


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