0

I have a question about the third for loop, how does it work please ?

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();

   }
}

The problem is I don't know the mechanics how it print out stars.

4

2 回答 2

1

The loop will take the variable star and loop and increment until it reaches the value of frequency[count]. So it will run the loop the same number of times as the value stored in frequency[count].

Each loop iteration it prints a star. At the end it prints a blank line.

The result is printing the number of stars as frequency[count] on a line.

于 2012-12-27T22:20:22.050 回答
1

Well lets go through the code then:

The second for loop which contains the third for-loop will loop 11 times since thats the length of frequencey. Okay that was easy.

Now the third for-loop iterates frequency[count] times, we don't know this value, but we know that it is an integer. So what third loop will do is simply to print out a star frequency[count] times. After that we're done with the third loop and a newline is printed by the second loop.

System.out.println("*" * frequency[count]);
于 2012-12-27T22:24:07.530 回答