【发布时间】:2011-05-12 09:30:55
【问题描述】:
系统:Windows Vista 32 位,Java 6.0.2
我有几个关于将字符转换为整数的问题。 我运行下面的代码,myInt 的值为 4:
char myChar = '4';
int myInt = myChar - '0';
现在,这种转换是 Java 自动完成的吗?是从 ascii '4' 中减去 '0' 的 ascii 值,然后在幕后转换为 int 吗?这让我感到困惑,因为当我尝试反向操作时,我必须将结果实际转换为 char:
int anotherInt = 5;
char newChar = anotherInt + '0'; //gives error
char newChar = (char)(anotherInt + '0'); //works fine
发生这种情况是因为 Java 自动将 (anotherInt + '0') 强制转换为 int,如第一个示例所示?谢谢你。
【问题讨论】:
-
用
ints 和longs 试试看会发生什么。int myInt = 1L