3.1 The if-else Statement
To write useful programs, we almost always need to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement:
if (x > 0)
{
System.out.println("x is positive");
}
The expression in parentheses is called the condition. If it is true, then the statements in brackets get executed. If the condition is not true, nothing happens.
A second form of conditional execution is alternative execution, in which there are two possibilities, and the condition determines which one gets executed. The syntax looks like:
if (x%2 == 0)
{
System.out.println("x is even");
}
else
{
System.out.println("x is odd");
}
If the remainder is zero, code prints a message x is even. If the condition is false, the second print statement is executed. The modulus operator % works on integers and yields the remainder when the first operand is divided by the second.
The following progam reads two numbers from keyboard and determine the maximum number.
import java.util.Scanner; // Needed for the Scanner class
/**
* This program demonstrates the if-else statement.
*/
public class Maximum
{
public static void main(String[] args)
{
int number1, number2; // store two numbers
int max; // store maximum of two numbers
// Create a Scanner object to read input.
Scanner console = new Scanner(System.in);
// Get two numbers from the user.
System.out.print("Enter an integer: ");
number1 = console.nextInt();
System.out.print("Enter another integer: ");
number2 = console.nextInt();
// Determine maximum of two.
if (number1 > number2)
{
max = number1;
}
else
{
max = number2;
}
System.out.println("Maximum number is " + max);
}
}
Output
Enter an integer: 5
Enter another integer: 16
Maximum number is 16
Enter another integer: 16
Maximum number is 16
No comments:
Post a Comment