go to previous page   go to home page   go to next page hear noise highlighting

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 ?


go to previous page   go to home page   go to next page