2015-12-15 101 views
0

我猜输出1这个代码,但不是说我得到的输出49,为什么我会得到完全不同的输出

的代码是

public static void main(String[] args) { 
     String str = "1+21"; 
     int pos = -1; 
     int c; 
     c = (++pos < str.length()) ? str.charAt(pos) : -1; 
     System.out.println(c); 
    } 

回答

6

someCondition ? a : b的结果是ab的常见类型。在这种情况下,str.charAt(pos)(一个字符)和-1(一个int)的常见类型是int。这意味着您的str.charAt(pos)值正被转换为int - 基本上,它被转换为unicode代码点,在这种情况下,它与其值为ASCII的值相同。

49是字符'1'的代码点。

如果你想获得为C的数字“1”,最容易做的事情是要减去的代码点“0”:

c = (++pos < str.length()) ? (str.charAt(pos) - '0') : -1; 

这工作,因为所有号码在unicode中是顺序的,从'0'开始。减去这些炭“0”的价值 - 也就是说,INT 48 - 你得到你想要的值:

'0' = 48 - 48 = 0 
'1' = 49 - 48 = 1 
... 
'9' = 57 - 48 = 9 
+0

非常感谢您的帮助 – nithinalways

0

charAt方法返回您传递位置的char值。在这里你将这个分配给一个int变量。所以这意味着你得到了特定char值的整数表示。 您的情况

int c = "1+21".charAt(0); -> actual char is 1 and the ASCII of that is 49 
相关问题