for(int charcode:message)

时间:2011-05-30 06:44:36

标签: java char

请允许我提一个愚蠢的问题。我目前正在做我的教程工作,但我没有得到(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();

    }

3 个答案:

答案 0 :(得分: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以获取更多信息。

答案 1 :(得分:2)

增强了循环。简而言之:它遍历message数组,并在每次迭代中将下一个值分配给charcode

相当于

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

注意 - 它将计数器命名为$i只是为了表明它是隐藏的并且在增强的for循环中不可用)

答案 2 :(得分:0)

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

这会在message中的项目上创建一个循环。每次通过时,charcode都设置为数组中的当前元素,直到所有项目都已打印完毕。它被称为foreach循环。

相关问题