Java Reference
In-Depth Information
A variable that holds a Boolean value is known as a Boolean variable . The boolean data
type is used to declare Boolean variables. A boolean variable can hold one of the two values:
true or false . For example, the following statement assigns true to the variable lightsOn :
Boolean variable
boolean lightsOn = true ;
true and false are literals, just like a number such as 10 . They are reserved words and
cannot be used as identifiers in your 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 ”, 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.currentTimeMillis() / 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 .
Boolean literals
VideoNote
1
+
7?
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
6
7
8 // Create a Scanner
9 Scanner input = new Scanner(System.in);
10
11 System.out.print(
12
int number1 = ( int )(System.currentTimeMillis() % 10 );
generate number1
generate number2
int number2 = ( int )(System.currentTimeMillis() / 7 % 10 );
show question
"What is " + number1 + " + " + number2 + "? " );
13
14
15
16 System.out.println(
17 number1 + " + " + number2 + " = " + answer + " is " +
18 (
int answer = input.nextInt();
display result
number1 + number2 == answer
));
19 }
20 }
What is 1 + 7?
1 + 7 = 8 is true
8
What is 4 + 8?
4 + 8 = 9 is false
9
line#
number1
number2
answer
output
5
4
6
8
14
9
16
4 + 8 = 9 is false
 
 
Search WWH ::




Custom Search