If you wanted something to occur based on a probability of say 40% in a Java game or simulation, then you could use the Math.random method like this.Where HI is the highest integer and LO is the lowest integer in the desired range of integer values. A general formula to use for generating a random integer over a range of values is.In the statement below you must assume that num is a double. The Math.floor method could be used instead of typecasting with the (int) cast operator as long as you store the returned value into a double variable.Num = (int) Math.random() * 6 + 1 // always equals one Num = (int) (Math.random() * 10) - 4 // -4 <= num <= 5īe careful to use the extra set of parentheses in the examples above since Num = (int) (Math.random() * 2) + 1 // 1 or 2 (simulated coin flip) By typecasting the result to an integer and truncating the decimal places, we can ensure that only whole numbers are produced as in:.You can manipulate this returned value by turning it into an integer or "spreading out" the range of possible values.The static method named random in the Math class can be used to create a random decimal value that is greater than or equal to 0.0 and less than 1.0.įor example, the following statement displays a random decimal value such as 0.34.So it is proper to call these values pseudorandom rather than random. It is technically impossible to create a truly random value with a computer since any available built-in method or process for creating a random value relies on some determinate mechanism such as the computer's system clock.Objective #1: Use the Math.random static method for random number generation to create
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |