2011-05-30 30 views
0

允許我問一個愚蠢的問題。我目前正在做我的教程工作,但我沒有得到(charcode:message)的意思。for(int charcode:message)

public static void main(String[] args) { 
     final int [] message = 
     {82, 96, 103, 103, 27, 95, 106, 105, 96, 28}; 
     //the secret message 
     final int key = 5; 
     //key to unlock the message 
     for (int charcode: message){ 
      System.out.print((char)(charcode + key)); 

     } 
     //termincate with a newline 
     System.out.println(); 

    } 
+1

它的簡寫'爲(INT i = 0;我 bdares 2011-05-30 06:46:19

+0

請參閱[Java中的增強for循環表示法](http://stackoverflow.com/search?q=enhanced+for+loop)。它是句法糖。 – 2011-05-30 06:46:46

回答

5

它被稱爲foreach。它可以讓你的每一個元素遍歷輕鬆數組中,下面的代碼將是「equivalant」:

for (int i = 0; i < message.length; i++) 
    System.out.print((char)(message[i] + key)); 

或者:

for (int i = 0; i < message.length; i++) 
{ 
    int charcode = message[i]; 
    System.out.print((char)(charcode + key)); 
} 

看一看在documentation一些更多的信息, 。

+0

@MByD:請注意,我已經在equivalant中引用了引號。如果您認爲這是錯誤的,請隨時編輯我的答案。 – Kevin 2011-05-30 11:25:48

+0

你是對的。我只是覺得值得一提。 :) – MByD 2011-05-30 11:53:19

0
for (int charcode: message){ 
    System.out.print((char)(charcode + key)); 
} 

這會在message中的項目上創建一個循環。每次通過時,charcode都被設置爲數組中的當前元素,直到所有項目都已打印完畢。它被稱爲foreach循環。

2

它是增強用於循環。簡而言之:它遍歷message陣列並在每次迭代中將的下一個值分配給charcode

這相當於

for(int $i=0; $i<message.length; $i++) { 
    int charcode = message[$i]; 
    System.out.print((char)(charcode + key)); 
} 

- 它命名爲計數器$i只是爲了顯示,它是隱藏的,在不使用增強的for循環)