Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and the Yahoo Answers website is now in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Can you explain me this Java code ?

import java.util.Random;

class Array_Elements {

public static void main(String arg[]){

Random rand = new Random();

int freq[]= new int[7];

for (int roll = 1;roll<=1000;roll++){

++freq[1+rand.nextInt(6)];

}

System.out.println("Face\tFrequency");

for (int face=1;face<freq.length;face++){

System.out.println(face+"\t"+freq[face]);

}

}

}

I know that it's a program like a dice, Dice is rolled 1000 times and

it will tell us how many times a number is rolled between 1 to 6 obviously (like a dice)

I just don't get how it does that. I get almost every part of this code

I just don't understand this line ( ++freq[1+rand.nextInt(6)]; )

What does it do ?

Can you please explain it from the scratch (That line).

Thank you in advance.

2 Answers

Relevance
  • John
    Lv 7
    7 years ago

    rand.nextInt(6) = generates a random number between 0 and 5

    1 + ... = as there is no dice number is zero (0) then add 1 to the proceeding result.

    freq[x] = freq[1] ... freq[6] represents the number of the dice, freq[1] means 1

    ++freq[2] = means adding 1 to the dice number (2) for frequency, actually it is odd, normally presenting freq[2]++ would be easy to understand

    If you understand an array is zero based and how to use it, you would never write a code like this and keep adding 1 to the result...

    try this...

    Random rnd = new Random();

    int[] freq = new int[6];

    // simulates a 6-face dice rolling and its frequency...

    for (int i = 0; i < 1000; i++) {

    int value = rnd.nextInt(6);

    freq[value]++;

    }

    // displays the frequency results...

    System.out.println("Face\tFrequency");

    for (int i = 0; i < freq.length; i++) {

    System.out.format("%d\t%d%n", i + 1, freq[i]);

    }

  • justme
    Lv 7
    7 years ago

    freq is an array of 7 integers, so whatever random number comes up (1 - 6), that is the integer in the array that gets incremented.

    1+rand.nextInt(6) gives a number 1- 6 and this number is used as the index into the freq array.

    It would be similar to doing this:

    ++freq[3]; or ++freq[6]; etc...

Still have questions? Get your answers by asking now.