#14 Java Control Statements

Control Statements - The if Statement

                      if(condition) statement;
                     else statement;

Note:
 else clause is optional
 targets of both the if and else can be blocks of statements.

The general form of the if, using blocks of statements, is:

              if(condition) 
        {
                statement sequence 
          } 
             else 
       { 
             statement sequence
           }

If the conditional expression is true, the target of the if will be executed; otherwise, if it exists, the target of the else will be executed. At no time will both of them be executed. The conditional expression controlling the if must produce a boolean result.

Example:

Guessing Game(Guess.java)

The program asks the player for a letter between A and Z. If the player presses the correct letter on the keyboard, the program responds by printing the message **Right **.

// Guess the letter game.

class Guess
{
public static void main(String args[])
throws java.io.IOException{
 char ch, answer = 'K';
System.out.println("I'm thinking of a letter between A and Z.");
 System.out.print("Can you guess it: ");
ch = (char) System.in.read(); // read a char from the keyboard
 if(ch == answer)
System.out.println("** Right **");

   }

 }

Extending the above program to use the else statement:

// Guess the letter game, 2nd version. 
class Guess2 { 
public static void main(String args[]) 
throws java.io.IOException {
 char ch, answer = 'K'; 
System.out.println("I'm thinking of a letter between A and Z.");
 System.out.print("Can you guess it: ");
 ch = (char) System.in.read(); // get a char 
     
   if(ch == answer) 
               System.out.println("** Right **");
  else 
              System.out.println("...Sorry, you're wrong.");
          }
}

Comments

Popular Posts