Thursday, March 10, 2005

Casting

int i = (int) (Math.random() * 5);

Sometimes it is OK to risk loosing information.

Casting public class Dice { public static void main(String[] args) { // prints a number greater than or equal to 1.0 and less than 7.0. System.out.println((Math.random() * 6) + 1); // prints 1, 2, 3, 4, 5 or 6 System.out.println((int) (Math.random() * 6) + 1); } } Sometimes, loosing information is exactly what we want. Math.random() * 6 + 1 returns a pseudorandom-number, say 6.385438106465076. This is not excactly what we want, if the number is supposed to represent the eyes on a dice. We need to get rid of the decimal part. The problem is solved by using casting to loose the information: (int) (Math.random() * 6) + 1

No comments: