Java Reference
In-Depth Information
two  values: true or false . For example, the following statement assigns true to the
variable lightsOn :
boolean lightsOn = true ;
true and false are literals, just like a number such as 10 . They are treated as reserved words
and cannot be used as identifiers in the program.
Suppose you want to develop a program to let a first-grader practice addition. The program
randomly generates two single-digit integers, number1 and number2 , and displays to the student
a question such as “What is 1
Boolean literals
7?,” as shown in the sample run in Listing 3.1. After the student
types the answer, the program displays a message to indicate whether it is true or false.
There are several ways to generate random numbers. For now, generate the first integer
using System.currentTimeMillis() % 10 and the second using System.current-
TimeMillis() / 7 % 10 . Listing 3.1 gives the program. Lines 5-6 generate two numbers,
number1 and number2 . Line 14 obtains an answer from the user. The answer is graded in
line 18 using a Boolean expression number1 + number2 == answer .
+
VideoNote
Program addition quiz
L ISTING 3.1
AdditionQuiz.java
1 import java.util.Scanner;
2
3 public class AdditionQuiz {
4
public static void main(String[] args) {
5
int number1 = ( int )(System.currentTimeMillis() % 10 );
generate number1
generate number2
6
int number2 = ( int )(System.currentTimeMillis() / 7 % 10 );
7
8 // Create a Scanner
9 Scanner input = new Scanner(System.in);
10
11 System.out.print(
12
show question
"What is " + number1 + " + " + number2 + "? " );
13
14
int number = input.nextInt();
15
16 System.out.println(
17 number1 + " + " + number2 + " = " + answer + " is " +
18 (number1 + number2 == answer));
19 }
20 }
display result
What is 1 + 7? 8
1 + 7 = 8 is true
What is 4 + 8? 9
4 + 8 = 9 is false
line#
number1
number2
answer
output
5
4
6
8
14
9
16
4 + 8 = 9 is false
 
 
Search WWH ::




Custom Search