DEV Community

Cover image for Generating Random Numbers
Paul Ngugi
Paul Ngugi

Posted on

Generating Random Numbers

You can use Math.random() to obtain a random double value between 0.0 and 1.0, excluding 1.0.

Suppose you want to develop a program for a first-grader to practice subtraction. The program randomly generates two single-digit integers, number1 and number2, with number1 >= number2, and it displays to the student a question such as “What is 9 - 2?” After the student enters the answer, the program displays a message indicating whether it is correct. The previous programs generate random numbers using System.currentTimeMillis(). A better approach is to use the random() method in the Math class. Invoking this method returns a random double value d such that 0.0 … d 6 1.0. Thus, (int)(Math.random() * 10) returns a random single-digit integer (i.e., a number between **0 and **9).
The program can work as follows:

  1. Generate two single-digit integers into number1 and number2.
  2. If number1 < number2, swap number1 with number2.
  3. Prompt the student to answer, "What is number1 – number2?"
  4. Check the student’s answer and display whether the answer is correct.

Image description

To swap two variables number1 and number2, a temporary variable z (line 13) is used to first hold the value in number1. The value in number2 is assigned to number1 (line 14), and the value in z is assigned to number2 (line 15).

Top comments (0)