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


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