0

I'm a newbie in java. I was going through some tutorials and came across this code I was not able to understand the code. Please explain what it means.

class Randoms
{
    public static void main(String[] args)
    {
        Random rand = new Random();
        int freq[] = new int[7];
        for(int roll = 1; roll < 10; roll++)
        {            
             (++freq[1 + rand.nextInt(6)]);
        }
...
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
user3864263
  • 377
  • 2
  • 14

4 Answers4

4

Line by line:

Random rand = new Random(); create new instance of the Random object, this is responsible for the creation of random numbers.

int[] freq = new int[7]; create a new int array that can store 7 elements, with indices from 0...6. It is worth noting that in Java, the ints stored in the array are initialized to 0. (This is not true for all languages, an example being C, as in C the int arrays initially store memory junk data, and must be explicitly initialized to zero).

for(int roll = 1; roll < 10; roll++) this rolls 9 times (because 1...9, but it's better practice to go from 0)

(++freq[1 + rand.nextInt(6)]); this line is something that you shouldn't ever do in this sort of fashion, because it's a monstrosity as you can see.

Do something like this:

    for(int roll = 0; roll < 9; roll++)
    {            
         int randomNumber = rand.nextInt(6); //number between 0...5
         int index = 1 + randomNumber; //number between 1...6
         freq[index]++; //increment the number specified by the index by 1
                        //nearly equivalent to freq[index] += 1;
    }

So basically it randomizes the number of 9 dice throws, and stores the dice throw count (or so it calls it, frequency) in the array.

Thus, it's simulating 9 dice throws (numbers from 1...6), and each time it "rolls" a particular number, it increases the number stored in the array at that specific location.

So in the end, if you say:

    for(int i = 1; i <= 6; i++)
    {
        System.out.println("Thrown " + freq[i] + " times of number " + i);
    }

Then it will be clearly visible what's happened.

EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • 1
    I assumed there was actually more code after what the OP showed us, otherwise he/she would have had some more `}` characters at the end. I'm guessing that the undisclosed part is a loop that prints out the values in the array, in some form. – Dawood ibn Kareem Jul 22 '14 at 11:06
  • Considering the quality of this "tutorial code", I have a feeling it just said `System.out.println("" + freq[i]);` with near-zero explanation. – EpicPandaForce Jul 22 '14 at 11:07
  • 1
    You may well be right. By the way, it may be worth editing your answer to mention that the array is in fact initialised to zeroes, as you hinted at in the comments. – Dawood ibn Kareem Jul 22 '14 at 11:09
  • @DavidWallace based on a google search, i found pastebin snippets and http://www.toppersarena.com/index.php/forum/22-aniruddh-s-programming-blogs/1439-array-elements-as-counters to be honest I wouldn't want to learn Java from here – EpicPandaForce Jul 23 '14 at 09:53
1
(++freq[1 + rand.nextInt(6)]);   // this line of code.

The above line of code is pre-incrementing the value of freq[] array at the specified position,i.e., 1+rand.nextInt(6) --- referred value is ++freq[some-position to be evaluated] which we will evaluate below.

This rand.nextInt(6) will generate an integer number lesser than 6 and greater than 0,as it is a pre-defined method of Random Class ,randomly.We can't predict it. And,then say number generated is 4. SO, 1+rand.nextInt(6)=5.

Hence,your code would simplify to (++freq[1 + rand.nextInt(6)]) OR `(++freq[5]).

So,simplification of this code will be equivalent to a number which equals 1 more than 6th element of array freq[].

  // as freq[5] is the 6th element of the array freq[].

Also,there are some other points which SIR David Wallace suggested me to include which I would like to explain a bit more.It goes below :-

  1. ++a here ++ is called pre-increment operator and it increases the value of a by 1. There also exists an altered reverse version of it.

  2. a++ here this ++ is called post-increment operator and it also increases the value of a by 1.But,WAIT,you might have thought that there aren't differences,but there are.

For the differences potion,I'd like to suggest to have a reading of What is the difference between pre-increment and post-increment in the cycle (for/while)?, though it is questioned in sense of C++,the same is in Java too!

Community
  • 1
  • 1
Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
  • I don't feel it's valid to talk about "output of this code". There is no output shown in the code snippet. The returned value from the `++` operator is not being used at all. Also, if I don't know what "pre-incrementing" is (frankly, I'm not even sure there's such a word), this isn't going to make much sense to me. – Dawood ibn Kareem Jul 22 '14 at 11:24
  • @DavidWallace-I already mentioned in my answer that I am only talking about this particular piece of code,not the whole.Secondly,any result which comes out of an expression can be considered as an output.If you contradict,please explain as to where I am wrong! Also,I'll be happy than ever to modify it! – Am_I_Helpful Jul 22 '14 at 11:27
  • I explained already. Talking about "pre-incrementing" isn't helpful, when the OP has already indicated that they don't know what `++` does. And talking about "output of this code" is just wrong; because the code doesn't actually have any output. The key thing it does is modify values in an array - but this is something that you inexplicably haven't mentioned at all. – Dawood ibn Kareem Jul 22 '14 at 11:31
  • @DavidWallace-Sorry for mentioning again SIR,but,I already mentioned in my previous comment that any result which comes out of an expression can be considered as an output. Also,I somewhat agree to your first part related to `++`.But,I don't believe he might not know that.Any book/tutorial before suggesting to code would surely tell him about `++`.Also,you're incorrect as you could see the first comment on `ug_`'s answer.You only commented below clarifying and I was the one who upvoted your comment and below,left my comment.I hope you agree,OR,else,I am afraid I'll have to include that too. – Am_I_Helpful Jul 22 '14 at 11:37
  • @DavidWallace-Also,my answer's last line clearly mentions output as `1 more than 6th element of array freq[]`,if you could check it again! But,SIR,please comment to make me feel comfortable about it! – Am_I_Helpful Jul 22 '14 at 11:40
  • If you don't want to improve your answer as per my suggestions, that's fine with me. – Dawood ibn Kareem Jul 22 '14 at 11:46
  • @DavidWallace-Ok,I'll surely do as per your suggestions!THANKS. – Am_I_Helpful Jul 22 '14 at 11:48
  • @DavidWallace-Please check whether this much is fine OR should I be more specific at it! – Am_I_Helpful Jul 22 '14 at 12:00
1
// Create a new Random Object, this helps you generate random numbers
Random rand = new Random();
// create a integer array with 7 integers
int freq[] = new int[7];
// loop 9 times
for(int roll = 1; roll < 10; roll++)
{
    // rand.nextInt(6) generates a number between 0 and 5 (<6). add one to it
    // ++ adds one to the integer in the array that is at the index of 1-6.
    (++freq[1 + rand.nextInt(6)]);
}

Some strange things about this code:

  • Roll loop starts at 1 then goes to 10 so at first glance it would seem to loop 10 times but actually runs 9 times.
  • The ++ inside the loop would generally be located on the right and could lead to some confusion among newer programmers.
  • freq[1 + rand.nextInt(6)] causes freq[0] to never be used.
ug_
  • 11,267
  • 2
  • 35
  • 52
1

At first a new object of the Random-Class and an array with 7 elements are created. Each element of the Array has the value 0. Inside the for-loop you randomly pick element 2 to 7 of the Array and increase its current value by 1. This is done 9 times.

Your code will never pick the first element of the Array which has the index 0.

I would rewrite the code to make it more clear:

Random rand = new Random();
int freq[] = new int[6];
int randomIndex = 0;
for(int roll = 0; roll < 9; ++roll)
{
    randomIndex = rand.nextInt(6);
    freq[randomIndex] = freq[randomIndex] + 1;
}

This code has not been tested, but it should basicly do the same.

Denuath
  • 130
  • 1
  • 6