Java Reference
In-Depth Information
You can use
Math.random()
to obtain a random double value between
0.0
and
1.0
,
excluding
1.0
.
Key
Point
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 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:
VideoNote
Program subtraction quiz
0.0
…
d
6
1.0.
random()
method
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.
The complete program is shown in Listing 3.4.
L
ISTING
3.4
SubtractionQuiz.java
1
import
java.util.Scanner;
2
3
public class
SubtractionQuiz {
4
public static void
main(String[] args) {
5
// 1. Generate two random single-digit integers
random number
6
int
number1 = (
int
)(Math.random() *
10
);
7
int
number2 = (
int
)(Math.random() *
10
);
8
9
// 2. If number1 < number2, swap number1 with number2
10
if
(number1 < number2)
{
11
int
temp = number1;
12 number1 = number2;
13 number2 = temp;
14 }
15
16
// 3. Prompt the student to answer "What is number1 - number2?"
17 System.out.print
18 (
"What is "
+ number1 +
" - "
+ number2 +
"? "
);
19 Scanner input =
new
Scanner(System.in);
20
21
22
get answer
int
answer = input.nextInt();
// 4. Grade the answer and display the result
23
24 System.out.println(
"You are correct!"
);
25
else
26 System.out.println(
"Your answer is wrong\n"
+ number1 +
" - "
27 + number2 +
" is "
+ (number1 - number2));
28 }
29 }
if
(number1 - number2 == answer)
check the answer
What is 6 - 6?
You are correct!
0