如何在Java中将字符转换为int?
(我是Java编程新手)
例如,我有:
char x = '9';
我需要得到撇号中的数字,数字9本身。 我试着做了以下几件事
char x = 9;
int y = (int)(x);
但它不起作用
那么我应该怎么做才能得到撇号中的数字呢
你可以在下面搜索框中键入要查询的问题!
(我是Java编程新手)
例如,我有:
char x = '9';
我需要得到撇号中的数字,数字9本身。 我试着做了以下几件事
char x = 9;
int y = (int)(x);
但它不起作用
那么我应该怎么做才能得到撇号中的数字呢
# 1 楼答案
您可以使用Character类中的静态方法从char中获取数值
# 2 楼答案
ASCII表的排列使得字符
'9'
的值比'0'
的值大九;字符'8'
的值比'0'
的值大八;等等因此,您可以通过减去
'0'
得到十进制数字字符的int值# 3 楼答案
如果您想要获取字符的ASCII值,或者只是将其转换为int,则需要从char转换为int
什么是演员?强制转换是当我们显式地从一个primitve数据类型或一个类转换到另一个时。这里有一个简单的例子
在本例中,我们有一个字符('a'),并将其转换为整数。打印出这个整数将得到ASCII值“a”
# 4 楼答案
如果您有
char '9'
,它将存储其ASCII代码,因此要获取int值,您有两种方法或
事实上,这也是有效的:
您存储
9
代码,它对应于一个horizontal tab
(您可以在打印时看到String
,但您也可以在上面看到的int
中使用它