系統:Windows Vista 32位,Java 6.0.2在Java中將字符轉換爲Ints
我有幾個關於將字符轉換爲整數的問題。 我運行下面的代碼,使敏用值4:
char myChar = '4';
int myInt = myChar - '0';
現在,這是轉換的東西,Java的自動呢?從ascii'4'減去'0'的ascii值,然後在幕後投射到int?這是混淆了我,因爲當我嘗試反向操作,我必須真正把結果作爲字符:
int anotherInt = 5;
char newChar = anotherInt + '0'; //gives error
char newChar = (char)(anotherInt + '0'); //works fine
這是發生的歷史,因爲Java的自動鑄造(anotherInt +「0」)爲int ,如第一個例子中那樣?謝謝。
試着用'int'和'long's來看看會發生什麼。 'int myInt = 1L' – 2010-11-19 01:15:04