Read this chapter, which reviews how computers make decisions using if statements. As you read this tutorial, you will understand that sometimes it is important to evaluate the value of an expression and perform a task if the value comes out to be true and another task if it is false. In particular, try the simulated program under the heading "Simulated Program" to see how a different response is presented to the user based on if a number is positive or negative.
Pay special attention to the "More Than One Statement per Branch" header to learn how the 'else' statement is used when there is more than one choice.
3. Decisions
Answer:
Two.
Decisions
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; public 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
.
Indenting: Indent the "true branch" and "false branch" one level in from the if
and else
. This makes it easier for a human (you) to see the logic of the program. However, the compiler ignores indenting.
Sensible indenting and program layout is important. You want to make it as clear as possible what a program is doing. Often CS departments in schools and industry have formatting standards. It is important to be consistent. Use the same number of spaces every time you indent. Often, programmers use two, three, or four spaces.
Withoutproperuseofspaceandindentsseeingthelogicandunderstandingaprogramsometimesbecomesveryhard.
Question 3:
What happens if the user enters anything other than exactly the character Y ?