myRandom.nextInt(10) + 1
Random myRandom=new Random();
System.out.print(myRandom.nextInt(10) + 1);
System.out.print(" ");
/ … And so on.
This program was run several times with the results shown below. Stare briefly at the image and notice two trends:
The Java Virtual Machine jumps through hoops to maintain these trends. That’s because cranking out numbers in a random fashion is a tricky business. Here are some interesting facts about the process:
A number is random only when it’s one in a disorderly collection of numbers. More precisely, a number is random if the process used to generate the number follows the two preceding trends. When they’re being careful, scientists avoid the term random number and use the term randomly generated number instead.
To generate numbers in a truly random fashion, you need a big tub of ping-pong balls, like the kind they use in state lottery drawings. The problem is, most computers don’t come with big tubs of ping-pong balls among their peripherals. So, strictly speaking, the numbers generated by Java’s Random class aren’t random. Instead, scientists call these numbers pseudorandom.
For example, if you toss a coin twice, and get heads both times, are you more likely to get tails on the third flip? No. It’s still 50-50.
If you have three sons, and you’re expecting a fourth child, is the fourth child more likely to be a girl? No. A child’s gender has nothing to do with the genders of the older children. (I’m ignoring any biological effects, which I know absolutely nothing about. Wait! I do know some biological trivia: A newborn child is more likely to be a boy than a girl. For every 21 newborn boys, there are only 20 newborn girls. Boys are weaker, so we die off faster. That’s why nature makes more of us at birth.)
Dr. Barry Burd holds an M.S. in Computer Science from Rutgers University and a Ph.D. in Mathematics from the University of Illinois. Barry is also the author of Beginning Programming with Java For Dummies, Java for Android For Dummies, and Flutter For Dummies.