Two.
The windshield wiper decision is a two-way decision (sometimes called a binary decision). The decision seems small, but in programming, complicated decisions are made of many small decisions. Here is a program that implements the wiper decision:
import java.util.Scanner; class RainTester { public static void main (String[] args) { Scanner scan = new Scanner( System.in ); String answer; System.out.print("Is it raining? (Y or N): "); answer = scan.nextLine(); if ( answer.equals("Y") ) // is answer exactly "Y" ? System.out.println("Wipers On"); // true branch else System.out.println("Wipers Off"); // false branch } }
The user is prompted to answer with a single character, Y or N :
System.out.print("Is it raining? (Y or N): ");
The Scanner
reads in whatever the user enters (even if the user enters more than one character):
answer = scan.nextLine();
The if
statement tests if the user entered exactly
the character Y (and nothing else):
if ( answer.equals("Y") ) // is answer exactly "Y" ?
If so, then the statement labeled "true branch" is executed. Otherwise, the statement labeled "false branch" is executed.
The "true branch" is separated from the "false branch" by the reserved word else
.
What happens if the user enters anything other than exactly the character Y ?