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
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.
See more on this question at Stackoverflow