的問題說,這一切,這裏是代碼:爲什麼char連接返回「int」sum?
public class Chars
{
public static void main(String[] args){
Chars c = new Chars();
String res = c.test("abcd");
System.out.println(res);
}
public String test(String str){
String res = "";
res += str.charAt(0) + str.charAt(2);
return res;
}
}
這將返回:「196」,這是a
和c
的ASCII值的總和! 這是爲什麼發生? ,我期望得到「ac」。 如果我修改在這樣的測試()方法的第二行:
res = res + str.charAt(0)+str.charAt(2);
結果確實是「AC」。 請有人幫助我這個疑問。我只是無法找到答案!
非常感謝您的回答,一個非常好的解釋。但是,在第一種情況下,我使用「+ =」不應該表示「res + str.charAt(0)...」我的意思是什麼時候添加「res」的當前值?我認爲這就像首先添加「res」的實際值,然後添加其他操作數,但似乎是相反的方式。 – FraK
這是因爲'+ ='的優先級低於'+',所以'+'首先出現。 – rgettman
非常感謝您的解釋,現在已經編程了將近2年,並且仍然感到困惑或忘記了這些小事情:P – FraK