数组的预增量

时间:2015-08-19 19:11:56

标签: java arrays post-increment

任何人都可以解释这段代码的输出吗?我一直很难理解,但我只是不明白。

public static void main(String ars[]) {
    int responses[] = {1,2,4,4};
    int freq[] = new int[5];

    for(int answer = 1; answer < responses.length; answer++) {
        ++freq[responses[answer]];
    }

    for (int rating = 1; rating < freq.length; rating++)
         System.out.printf("%6d%10d\n", rating, freq[rating]);
}

输出

 1         0
 2         1
 3         0
 4         2

2 个答案:

答案 0 :(得分:0)

我尝试过简单的事情,这样你就可以看到发生了什么:

    int responses[] = new int[4];
    responses[0] = 1;
    responses[1] = 2;
    responses[2] = 4;
    responses[3] = 4;

    int freq[] = new int[5];

    for(int answer = 1; answer < 4; answer++)
    {
        int x = responses[answer];
        freq[x] = freq[x] + 1;
    }

    for (int rating = 1; rating < 5; rating++)
    {  
         //Print 6 spaces and then the rating variable
         //Print 10 spaces then the integer at freq[rating]

         System.out.printf("%6d%10d\n", rating, freq[rating]);
    } 

我会查看++ prefix & postfix

答案 1 :(得分:0)

在第一个循环++ freq [responses [answer]];意思是:

  • respon [answer]从响应数组索引中获取值。
  • Freq [value] check&amp;从Filter数组索引中获取值。
  • ++ Freq [value]将值1添加到Freq [value]。