2017-06-26 17 views
0

我編碼的東西只是爲了好玩,發現一些非常混亂的東西。使用不同的數據類型輸出?

我先寫這樣的代碼。

public class Testing(){ 
    public static void main(String args[]){ 
    int a=1; 
    char b='A'; 
    System.out.print('A'+a); 
     } 
} 

輸出是66?

然後我修改這樣的第二個代碼。

public class Testing(){ 
     public static void main(String args[]){ 
     int a=1; 
     char b='A'; 
     System.out.print((char)('A'+a)); 
      } 
    } 

第二代碼的輸出是B.

有人可以幫我解釋WHA這裏發生。

謝謝!

回答

0

當你做

System.out.print('A'+a); 

「A」將被用作一個數(它實際上是一個截尾整數),結果將被表示爲一個數...

當你做:

System.out.print((char)('A'+a)); 

你流延到一個char所以結果將在ASCII什麼都被映射到66

0

當您添加charint(如'A'+a)時,char被升級爲int,結果爲int

因此,第一個片段打印一個int

在第二個片段你投的是intchar,所以顯示的字符'B',其int66

您的兩個片段調用PrintStream不同的方法 - 該第一轉換的intString和第二轉換一個charString

/** 
* 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)); 
} 
+0

在第一個代碼中,在將char轉換爲int之後,輸出結果應該也是int,但爲什麼它會出現66而不是其他數字,如43,56。是否有像ASCII這樣的轉換列表?謝謝! –

+0

@littletony'char'是一個數字類型,所以每個字符都有一個數值。 'A'的數值是65. 65 + 1是66. – Eran

+0

我明白你在說什麼。非常感謝! –

0

在內部,char是映射到一個字符符號的整數值。這就是爲什麼你可以將它添加到一個int。如果您告訴Java將結果作爲字符處理,您會得到一個字符。

0

'A'+a的情況下,該操作被視爲整數加法並將字符轉換爲等效的ASCII碼。因此結果是一個整數。

如果發生同樣的事情,並且最終輸出從您的ASCII轉換爲char,因爲您已鑄造。

+0

所以整數1代表alphet A,2代表B,等等等等?謝謝! –

相關問題