在java中将int转换为char [英] Convert int to char in java

查看:858
本文介绍了在java中将int转换为char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是一段代码片段,

int a = 1;
char b = (char) a;
System.out.println(b);

但是我得到的是空输出。

But what I get is empty output.

int a = '1';
char b = (char) a;
System.out.println(b);

我将获得1作为输出。

I will get 1 as my output.

有人可以解释一下吗?如果我想将int转换为一个char,如第一个片段,我该怎么办?

Can somebody explain this? And if I want to convert an int to a char as in the first snippet, what should I do?

推荐答案

int a = 1;
char b = (char) a;
System.out.println(b);

将打印出ascii值为1的字符可打印)。

will print out the char with ascii value 1 (start-of-heading char, which isn't printable).

int a = '1';
char b = (char) a;
System.out.println(b);

将打印出带有ascii值49(一个对应于'1')的字符

will print out the char with ascii value 49 (one corresponding to '1')

如果你想转换一个数字(0-9),你可以添加48和它,或类似 Character.forDigit(a,10) ;

If you want to convert a digit (0-9), you can add 48 to it and cast, or something like Character.forDigit(a, 10);.

如果要像ascii值一样转换 int 可以使用 Character.toChars(48)

If you want to convert an int as in ascii value, you can use Character.toChars(48) for example.

这篇关于在java中将int转换为char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆