2015-09-28 82 views
0

問題是:在控制檯中顯示什麼?如何用''聲明int,爲什麼是'2'== 50?

我真的有一些理解上的問題。

下面是代碼:

public static void felda(){ 
    char[] felda = {'2',0x31,48}; 
    for (int i = 0; i< felda.length; i++){ 
     System.out.println(" : " + felda[i]); 
    } 
    System.out.println(); 
} 
public static void feldb(){ 
    int[] feldb = {'2',0x31,48}; 
    for (int i = 0; i< feldb.length; i++){ 
     System.out.println(" : " + feldb[i]); 
    } 
    System.out.println(); 
} 
public static void feldc(){ 
    int [] feldc = {'2',0x31,48}; 
    for (int i = 0; i< feldc.length; i++){ 
     System.out.println(" : " + (char) feldc[i]); 
    } 
    System.out.println(); 
} 

所以,如果我在解決方案上運行是:

: 2 
: 1 
: 0 

: 50 
: 49 
: 48 

: 2 
: 1 
: 0 

所以我不明白是怎麼回事,甚至可能有「一個int definded 」。 我發現它很混亂如何int feldb = '2'結果是50和int feldb = 0x31結果是49 ..大壩這一切都很混亂。我希望有人能夠啓發我。

編輯:爲什麼char feldc = 48;導致0?

+1

HTTP://www.asciitable .com/ – QuakeCore

+1

http://www.ascii-code.com/ –

+0

相關:http://stackoverflow.com/questions/32051600/char-to-int-conversion –

回答

2

50是'2'字符的ASCII值。定義像它不是數字2 ..它給出一個字符的ASCII值。看到這個ASCII表,找到 '2' 字符

http://ascii.cl/index.htm?content=mobile

+0

從技術上講,它沒有給出字符的ASCII值,但是該字符的Unicode代碼點。他們恰好是一樣的。 –

4

在Java中,char代表一個Unicode字符。但它也實際上是一個無符號整數,2個字節,可以去從0到2 - 1

所以,

char c = '2'; 

初始化c字符 '2'。並且Unicode中字符'2'的數值爲50.

因此,如果將其打印爲字符,則會打印「2」。如果將其作爲數值打印(作爲int,使用int c = '2'),將打印50。

在做

char feldc = 48; 

初始化feldc與它的數字Unicode值是48字符,並且該字符是字符「0」。它是這樣相當於

char feldc = '0'; 

0x31是(這是0x前綴的意思)寫成一個十六進制文字的數字。當您編寫31時,該值爲十進制。它等於1 * 10 + 3 * 10 。

在十六進制中,鹼是16而不是10。所以0x31等於1×16 + 3 * 16 ,它等於49。