编写一个Java程序将整数转换为字符或整数转换为字符。在此编程语言中,我们必须显式地将整数转换为字符,因为我们将4字节整数转换为2字节字符。此技术将整数视为ASCII值并返回等效字符。
package NumPrograms;
import java.util.Scanner;
public class IntToChar1 {
private static Scanner sc;
public static void main(String[] args) {
sc= new Scanner(System.in);
System.out.print("Enter Any Integer Value = ");
int i = sc.nextInt();
char ch = (char)i;
System.out.println("Integer to Character = " + ch);
}
}

我们还可以通过添加字符'0'来将整数转换为字符。下面的代码使用了字符类型转换和'0'。
package NumPrograms;
public class IntToChar2 {
public static void main(String[] args) {
int i = 4;
int j = 9;
char ch1 = (char)(i + '0');
char ch2 = (char)(j + '0');
System.out.println(ch1);
System.out.println(ch2);
}
}
4
9
此示例使用`Character.forDigit`方法将整数转换为字符。对于十进制值,第二个参数为10,对于十六进制值,则为16。
package NumPrograms;
public class IntToChar3 {
public static void main(String[] args) {
int i = 9;
int j = 14;
int k = 1;
char ch1 = Character.forDigit(i, 10);
char ch2 = Character.forDigit(j, 16);
char ch3 = Character.forDigit(k, 10);
System.out.println(ch1);
System.out.println(ch2);
System.out.println(ch3);
}
}
9
e
1