This week's book giveaway is in the JavaScript forum. We're giving away four copies of Getting MEAN with Mongo, Express, Angular, and Node and have Simon Holmes on-line! See this thread for details.

i am writing a program, and i have made a randomGenrate method, which i would like to use in my rollDice method. Any help on how i can achieve this? Thanks

Stephen Foy - Microsoft Application Development Consultant

You need to check the Math.random() method carefully in the API. If I remember correctly, it returns a double number pseudo-randomly chosen between 0 and under 1, or something like 0 . . . 0.999999999....

Firstly, you should try to avoid using more than one random number generator within an app; if you hve two which are set off simultaneously, they may produce the same number each.

Secondly, if you multiply by 6, you will never get a "6;" you will get from 0 to 5.999999..., so you have to add 1 to your (int)(randomNumber * 6). Using round will actually bias your numbers; you will occasionally get a 6 or a 0, but with a lower probability than for 1 2 3 4 and 5.

The reason you are getting the same number printed out three times is that you have no means of changing the number in your loop in your rollOne() method.

Another way to get pseudo-random numbers would be the nextInt(6) method in the java.util.Random class. Again you would have to add 1.

So, a much simpler way to sort out the problem is EITHER

OR

When I first encountered the random number generating methods, I wrote out a class which mimics rolling a die, so I can use it whenever I want random numbers in a particular tange.

BTW: There is an example of random number generation in Deitel's book, where they add all the 1s, the 2s, the 3s etc, to count how many times each numebr comes up in, say, 10000 rolls, and they also count how many times the same number comes up twice in succession; if you have a die and roll it, you should get the same number twice once in 6 pairs, the same number thrice once in 36, etc etc.

Stephen Foy
Ranch Hand

Joined: Oct 17, 2005
Posts: 143

posted

0

Thanks for that, really helps. Oh and i managed to sort the getting a 0 problem, by using a while loop, which looped the number till it wasnt 0.

Or you could try java.util.Random.nextInt(6) + 1; if you read its documentation, there seems to have been some thought put into making sure that nextInt() does actually return a pseudo-random sequence of integers between 0 and 5 inclusive.

Stephen Foy
Ranch Hand

Joined: Oct 17, 2005
Posts: 143

posted

0

i managed to get it to do different random values, hope this is an appropriate way. Any suggestions?