r/learnjava • • Jan 18 '23

Learning java at 44

I've decided to learn java so I'm doing a short free course on udacity. I'm quite enjoying but I got stuck on a very basic bit of code and need some help. I'm generating random numbers for dice but now need to change the number of sides from 6 to 8 using parameters. I gone over my notes but still not quite sure where I've gone wrong. This course doesn't give me the answer anywhere so I can't see where I've gone wrong. I know (int sides) are the parameters I have to use but not sure how. Some guidance please!!

Public int roll Dice (int sides){ randomNumber=Math.random(); randomNumber=randomNumber*6; randomNumber=randomNumber+1; int randomInt=(int)randomNumber;

return randomInt; }

43 Upvotes

18 comments sorted by

View all comments

1

u/Housy5 Jan 18 '23

Is there a reason I see a lot of people use Math.random instead of the Random class?

1

u/Primary-Reputation-2 Jan 18 '23

What I learnt today was that random was in the math class. I might be wrong but I'm sure that's what they said

1

u/desrtfx Jan 18 '23

It is absolutely correct that there is Math.random().

Yet, it is also correct that there is a Random class that has several methods for generating random numbers. There is .nextInt(int range) that generates a random integer between 0 inclusive and range exclusive, there is .nextDouble() which does exactly what Math.random() does, as the latter is in fact using the former, and there are several other methods in this class.

Have a look java.util.Random class

Strange fact: there is also an undocumented .nextInt(int min, int max) method in newer Java versions that produces a random integer between min inclusive and max exclusive.

1

u/desrtfx Jan 18 '23

People learn Math.random() earlier as it is easier to use.

Using the Random class is a bit trickier especially in the early beginning when creating objects has not been introduced.