r/learnjava • u/Primary-Reputation-2 • 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; }
2
u/hugthemachines Jan 19 '23
I can see you already got good answers, I would just like to add something that can be good to know. There is a rule (of thumb) that says "Don't use magic numbers" and that means, don't add a number in your code that is without any kind of explanation.
Let's say a stick is 2 inches, instead of just putting a 2 in the code, we should have a variable with a good name. Like stickLengthInches = 2 or something fairly similar. Now people (or you in the future) who read the code can get a hint on what that number represents.
This may be something to think about on your ongoing code adventure.