2012-12-27 68 views
0

我有一个关于第三个循环的问题,请问它是如何工作的?第三个for循环如何工作?

public void outputBarChart() 
{ 
    System.out.println("Grade Distribution: \n"); 

    int frequency[] = new int[11]; 

    for(int oneGrade : grade) 
    { 
     ++frequency[oneGrade/10]; 
    } 

    for (int count = 0; count < frequency.length; count++) 
    { 
     if (count == 10) { 
      System.out.println("100"); 
     } 
     else { 
      System.out.printf("%02d-%02d: ", 
        count*10, count*10 + 9); 
     } 

     //the third for loop here ! 
     for (int star = 0; star < frequency[count]; star++){ 
      System.out.print("*"); 
     } 
     System.out.println(); 

    } 
} 

问题是我不知道它是如何打印出明星的机制。

+3

你能明确你的困惑吗?它只是在连续打印频率[count]'星星 –

+0

你不明白什么?这是一个简单的for循环,每次迭代都会打印一个'*'。 –

+3

运行调试器,跟踪执行并查看会发生什么。 –

回答

1

好让我们去通过代码然后:

for循环的第二个包含第三for循环将循环11次,因为这就是frequencey的长度。好吧,那很容易。

现在第三个for循环迭代frequency[count]次,我们不知道这个值,但我们知道它是一个整数。那么第三个循环会做什么只是打印出一颗明星frequency[count]次。之后,我们完成了第三个循环,第二个循环打印了一个换行符。

System.out.println("*" * frequency[count]); 
+0

感谢您的介绍,调试器工作得很好,我应该先尝试一下。 – Twocode

1

该循环将采用变量star并循环并递增,直到达到值frequency[count]。因此它将循环运行的次数与存储在frequency[count]中的值相同。

每个循环迭代它打印一颗星。最后它打印出一个空行。

结果是在一行上打印星号为frequency[count]