50 likes | 166 Vues
Introduction to Computer Programming Math Random. Dice. Random Number. Math class – knows PI, E, how to give a random # and how to do many math functions Method random – knows how to pick a random number between 0 and 1. double randBase = Math.random()
E N D
Random Number Math class – knows PI, E, how to give a random # and how to do many math functions Method random – knows how to pick a random number between 0 and 1. double randBase = Math.random() Now randBase is a double between 0 and 1, (ex: .051) but I want a dice value between 1 and 6 What can I do to randBase to get a dice value?
Random – Dice • Multiply by 6. • Any fraction * 6 will not equal 6 or more. • Ex: .051 * 6 = 3.06 • Chop off the remainder • Ex: 3 • Now I have a number between 0 and 5 • Add 1 to the number • Ex: 4
Random –Code To get dice: double randBox = Math.random(); int dieVal = (int) ( randBox * 6) + 1; How to get cards (13)?
Random – Code Alternate • Will this work: double x; // holds the random number we will generateintdiceValue; // holds the value of the dice that we calculate from the randomx = Math.random(); // generates a number between 0 and 1x = x *6; // multiplies that number times 6 so the number will be from 0 to 5diceValue = (int) x; // convert it to integer to chop off the decimal portiondiceValue = diceValue +1; // with dice, we want 1-6, not 0-5, so we add 1System.out.println ("The value of this die is " + diceValue);