Decisions
The "windshield wiper" decision is a two-way decision
(sometimes called a "binary" decision.)
It seems small, but in programs complicated decisions are
made of many small decisions.
Here is a program (suitable for "copy-paste-and-run") that includes a binary
decision.
import java.io.*;
class NumberTester
{
public static void main (String[] args) throws IOException
{
BufferedReader stdin =
new BufferedReader ( new InputStreamReader( System.in ) );
String inData;
int num;
System.out.println("Enter an integer:");
inData = stdin.readLine();
num = Integer.parseInt( inData ); // convert inData to int
if ( num < 0 ) // is num less than zero?
System.out.println("The number " + num + " is negative"); // true-branch
else
System.out.println("The number " + num + " is positive"); // false-branch
System.out.println("Good-by for now"); // always executed
}
}
|
The words if and else are markers that divide
decision into two sections.
The else is like a dividing line between the "true branch" and the
"false branch".
- The if statment always asks a question (often about a variable.)
- If the answer is "true" only the true-branch is exectued.
- If the answer is "false" only the false-branch is executed.
- No matter which branch is chosen,
execution continues with the statement after the false-branch.
Notice that a two-way decision is like picking which of two roads to take
to the same destination.
The fork in the road is the if statement, and the two roads come together
just after the false-branch.
|