Module 1 introduced the if statement. It is examined in detail here. The complete form of the if statement is if(condition) statement; else statement; where the targets of the if and else are single statements. The else clause is optional. The 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. To demonstrate the if(and several other control statements), we will create and develop a simple computerized guessing game that would be suitable for young children. In the first version of the game, 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 **.
The program is shown here:
// 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 **");
}
}
This program prompts the player and then reads a character from the keyboard. Using an if statement, it then checks that character against the answer, which is K in this case. If K was entered, the message is displayed. When you try this program, remember that the K must be entered in uppercase. Taking the guessing game further, the next version uses the else to print a message when the wrong letter is picked.
// 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.");
}
}
Friday, December 14, 2018
The if Statement
December 14, 2018
No comments
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment