import java.util.*;
import java.lang.*;
public class Main {
public static void main(String[] args) {
Random dice = new Random();
int a[]=new int [7];
for(int i = 1 ; i <=100;i++){
++a[1+dice.nextInt(6)];
}
System.out.println("Sno\t Values");
int no;
for(int i=1;i<a.length;i++){
System.out.println(i+"\t"+a[i]);
}
}
}
Sno Values
1 19
2 13
3 16
4 16
5 19
6 18
Can any one please explain this line "++a[1+dice.nextInt(6)]"
i know this program provides random number generated from 1-6 on how many times within the given value
-
1That line just counts the frequencies for each number.Sanket Makani– Sanket Makani2017年06月06日 09:55:46 +00:00Commented Jun 6, 2017 at 9:55
-
dice.nextInt will start its range from 0, so adding 1 will make it so dice.nextInt(6) will give you a result from 1 to 6 instead of 0 to 5Jan Somers JanS91– Jan Somers JanS912017年06月06日 09:58:20 +00:00Commented Jun 6, 2017 at 9:58
4 Answers 4
Mostly, that's just hard to read code. It would be at least slightly simpler to read (IMO) as
a[dice.nextInt(6) + 1]++;
... but it's easier still to understand it if you split things up:
int roll = dice.nextInt(6) + 1;
a[roll]++;
Note that there's no difference between ++foo and foo++ when that's the whole of a statement - using the post-increment form (foo++) is generally easier to read, IMO: work out what you're going to increment, then increment it.
Random.nextInt(6) will return a value between 0 and 5 inclusive - so adding 1 to that result gets you a value between 1 and 6 inclusive.
6 Comments
int a[]=new int [7]. Element 0 isn't used in the code.Yes, first you have
int a[]=new int [7];
which is an array that can hold 7 elements (valid indices being 0-6), all of which have an initial value of 0. Then
++a[1+dice.nextInt(6)];
is saying
int randomIndex = 1 + dice.nextInt(6); // <-- a random value 1 to 6 inclusive
a[randomIndex] = a[randomIndex] + 1;
Which is counting how many ones through sixes are rolled.
Comments
++a[1+dice.nextInt(6)]
dice.nextInt(6)= return an integer between 0 and 5
then you add 1 to that value, after that you get the element at that index in the array a and you increase that using the ++ operation
2 Comments
dice.nextInt(6); returns a value between 0 to 5.nextInt() returns a pseudorandom, uniformly distributed value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
So the value of 1+dice.nextInt(6) will fall between 1 to 6 (both inclusive) and increment the value of a[x] like a counter for x