• Post Reply Bookmark Topic Watch Topic
  • New Topic

Confused in Random Number Program  RSS feed

 
Inkoen Hagoed
Greenhorn
Posts: 2
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can anyone explain this program to me?

I'm actually confused about this statement ; ++freq[1+rand.nextInt(6)];
 
Stefan Evans
Bartender
Posts: 1837
10
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, welcome to the ranch

I see you tried to use the code tag but it didn't quite work. You have to nest your code inside the tags. The easiest way to do this is to select your "code" and THEN push the code button.
I've fixed that for you this time around :-)

That is quite a complex line of code. Its doing an awful lot, but if you break it down to its components it becomes clearer.


rand.nextInt(6) --> results in a random integer between 0 and 5 inclusive
1 + rand.nextInt(6) --> results in a integer between 1 and 6 inclusive - i.e. simulates rolling a six sided dice.
The "++" is shorthand for increment. Take the current value and add one to it.

That should be anough for you to figure out the rest :-)
 
Inkoen Hagoed
Greenhorn
Posts: 2
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for helping
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might find the code easier to understand like this:That has exactly the same effect as that code you had all squashed into a single line, but you need quite a bit of experience to understand such condensed code.

And welcome again
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you use a 7‑element array you can use indices 1...6 (I wrote 0...6 in line 4 a few minutes ago which was a mistake and have changed it to 1...6). In the array you forget about index 0, which means you can print like this:-It is actually not ideal to write numbers like 7 and 6. It would be better to write
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!