當您添加char
和int
(如'A'+a
)時,char
被升級爲int
,結果爲int
。
因此,第一個片段打印一個int
。
在第二個片段你投的是int
到char
,所以顯示的字符'B'
,其int
值66
。
您的兩個片段調用PrintStream
不同的方法 - 該第一轉換的int
到String
和第二轉換一個char
到String
:
/**
* Prints an integer. The string produced by <code>{@link
* java.lang.String#valueOf(int)}</code> is translated into bytes
* according to the platform's default character encoding, and these bytes
* are written in exactly the manner of the
* <code>{@link #write(int)}</code> method.
*
* @param i The <code>int</code> to be printed
* @see java.lang.Integer#toString(int)
*/
public void print(int i) {
write(String.valueOf(i));
}
/**
* Prints a character. The character is translated into one or more bytes
* according to the platform's default character encoding, and these bytes
* are written in exactly the manner of the
* <code>{@link #write(int)}</code> method.
*
* @param c The <code>char</code> to be printed
*/
public void print(char c) {
write(String.valueOf(c));
}
在第一個代碼中,在將char轉換爲int之後,輸出結果應該也是int,但爲什麼它會出現66而不是其他數字,如43,56。是否有像ASCII這樣的轉換列表?謝謝! –
@littletony'char'是一個數字類型,所以每個字符都有一個數值。 'A'的數值是65. 65 + 1是66. – Eran
我明白你在說什麼。非常感謝! –