Java Reference
In-Depth Information
the if and the switch constructs. The conditional operator (?:), which is
the only Java operator that contains three operands, is also used in deci-
sion-making constructs.
The if construct
The Java if construct consists of three elements:
1. The if keyword
2. A test expression, called a conditional clause
3. One or more statements that execute if the test expression is true
The following program, named BeepIf, displays the message
“BEEP-BEEP” if the user enters the number 1 or 2. Otherwise no message
is displayed. The code uses an if construct to test if the typed keystroke
matches the required numbers.
//
File name: BeepIf.java
//
Reference: Chapter 9
//
//
Java program to demonstrate simple decision
//
Topics:
//
1. Using the if construct
//
//
Requires:
//
1. Keyin class in the current directory
public class BeepIf
{
public static void main(String[] args)
{
int userInput;
userInput = Keyin.inInt("Enter 1 or 2 to beep: ");
if(userInput == 1 || userInput == 2)
System.out.println("BEEP-BEEP");
}
}
The BeepIf program uses a simple form of the Java if construct. The
compiler evaluates the expression in parentheses, following the if key-
word, which in this case is
if(userInput == 1 || userInput == 2)
The expression uses the logical OR operator (discussed in Chapter 8)
to create a compound condition. The parenthetical expression evaluates
to true if the variable userInput is equal to 1 or 2. If the expression evalu-
ates to true, then the statement that follows is executed. If the expression
Search WWH ::




Custom Search