Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am practicing using The new Boston tutorials, however there is one program that I don't fully understand. The program is designed to count the frequency of a number occuring in each dice roll and storing the results in an array. The line I have trouble with is ++freq[1+newDice.nextInt(6)]. I understand [1+newDice.nextInt(6)]; however how does the array know to increment each index by one each time the number occurs?

Random newDice = new Random ();

        int freq[] = new int [7];

        for(int i = 1; i<= 1000; i++)
        {
            ++freq[1+newDice.nextInt(6)];
        }

        System.out.println("Dice Number\tFrequency");
        for(int i = 1; i< freq.length; i++)
        {
            System.out.println(i+"\t\t"+freq[i]);

        }
share|improve this question

1 Answer 1

up vote 4 down vote accepted

It is incrementing the value stored at that position in the array. It is not incrementing the array index.

It is equivalent to:

int index = 1+newDice.nextInt(6);
int f = freq[index];
++f;
freq[index] = f;
share|improve this answer
    
Thanks Graham for clarifying. –  Calgar99 Mar 4 '13 at 14:30

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.