If-Else Examples
Each business has its own rules on how to report business related expenses, such as lunches and dinners. Often lunches and dinners are automatically approved for reimbursement if they are below a certain amount, but require special approval if that amount is exceeded. The following code shows a simple program to help with the reimbursement process. In this example the employee is allowed 20 dollars for lunch and 50 dollars for dinner:
int lunch = ?;
int dinner = ?;
if (lunch > 20)
{
int excessAmount = lunch - 20;
System.out.println("Fill out form 2311 to request the extra $" +
excessAmount + " of lunch reimbursement.");
}
else
System.out.println("Approved: $" + lunch + " for lunch");
if (dinner > 50)
{
int excessAmount = dinner - 50;
System.out.println("Fill out form 2312 to request the extra $" +
excessAmount + " of dinner reimbursement.");
}
else
System.out.println("Approved: $" + lunch + " for dinner");
The code above uses two seperate if-else statements. It is sometimes difficult for the beginning programmer to recognize where one if-else stops and the next one starts. In the above structure, the two if-else structures had the following bounds:

The next example intended as and exercise in identifying seperate if and if-else structures:
int x = ?;
int y = ?;
if (x > 100)
System.out.println("One");
else
System.out.println("Two");
if (x < 150)
System.out.println("Three");
if (x % 5 == 0)
System.out.println("Four");
if (x > y)
System.out.println("Five");
else
System.out.println("Six");
Can you identify the seperate if and if-else statements in the above example? What output is generated by the code above if x is 35 and y is 16? Or if x is 123 and y is 200? What is the output if x is 3000 and y is 14?
Group Statements with { }'s if Necessary
An if-else statement can only have a one statement (simple or compound) between the if (and its boolean condition) and the keyword . This code will not compile because the compiler cannot find the if that goes with the else (the if is too far away -- i.e., there is more than one statement between the if and the else):
if (x > 100)
System.out.println("Large number.");
System.out.println("More than one hundred.");
else
System.out.println("100 or less.");
The problem can be fixed by combining the two seperated statements into one compound (i.e. multi-part) statement with curly braces:
if (x > 100)
{
System.out.println("Large number.");
System.out.println("More than one hundred.");
}
else
System.out.println("100 or less.");
Cascading else-if's A series of if-else statements can be strung together. For example, lets say that you have been asked to sell magazine subscriptions and have been offered various prizes that you can earn, based on how many magazine subscriptions you sell. If you sell 20 subscriptions your prize is wristwatch, if you sell 50 then you get a small radio, and if you sell 100 subscriptions then you get a DVD player. If you sell 500 subscriptions then your prize is a new computer.
import java.util.*;
public class SellSubscriptions
{
public static void main(String [] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number of subscriptions that you sold: ");
String prize = "";
int sales = scan.nextInt();
if (sales >= 500)
prize = "computer!";
else
{
if (sales >= 100)
prize = "DVD player!";
else
{
if (sales >= 50)
prize = "radio";
else
{
if (sales >= 20)
prize = "wristwatch";
else
prize = "nothing";
}
}
}
System.out.println("Since you sold " + sales + " subscriptions, ");
System.out.println("your prize is: " + prize);
}
}
The code above prompts the user for their sales amount, then reports their prize. Here is a sample run of the program in which the user enters a sales amout of 53 subscriptions:

The first condition that resolves to true will end the processing of the above if-else. If a condition resolves to false, then the next if-else is processed.
For example, let's say that the user enters a sales amount of 600. Then the first condition resolves as true and its else clause is skipped (along with the three other if-else statements contained in that else clause):

In this example (where sales is 600) the prize variable is set to "computer!" and the rest of the cascading else-if is skipped.
If the user enters a sales amount of 53, then we will eventually arrive at the (sales >= 50) condition:

Notice that the if-else conditions keep getting checked until a true one is encountered, and once a true condition is encountered then the rest of the cascading else-if is skipped. Therefore, many programmers like to indent their cascading else-ifs so that it is very easy to visually scan down the list of conditions, looking for the first true one. With that in mind, it appears that the current preferred style for writing cascading else-ifs, among Java programmers is as follows (this is the same cascading else-if as show n above, just indented differently):
if (sales >= 500)
prize = "computer!";
else if (sales >= 100)
prize = "DVD player!";
else if (sales >= 50)
prize = "radio";
else if (sales >= 20)
prize = "wristwatch";
else
prize = "nothing";
Actually, the curly braces were removed from the else clauses (these were not required in the original version of the cascading else-if -- I had added them just to clarify where each else clause started and ended).
The final else is not required. If the final else is removed from the above example:
if (sales >= 500)
prize = "computer!";
else if (sales >= 100)
prize = "DVD player!";
else if (sales >= 50)
prize = "radio";
else if (sales >= 20)
prize = "wristwatch"; // No trailing else after this if
then it is possible that not a single statement in the cascading else-if is performed. In the above example nothing happens (no statement is performed) if the sales amount is less than twenty.
Which If For This Else?
It’s easy to tell that this else goes with the if before it...
int num = ?;
if (num > 10)
System.out.println("Big");
else
System.out.println("Small");
But which if does this else pair up with?
if (num > 6)
if (num < 12)
System.out.println("close! ");
else
System.out.println("Sorry! ");
GENERAL RULE: An else is always paired with the nearest possible if.
Therefore, the above code is indented very badly. It would be better to indent it this way:
if (num > 6)
if (num < 12)
System.out.println("close!");
else
System.out.println("Sorry");
For the code shown above, what output is generated if num is 3? If num is 10?
Some curly braces could be added just to clarify the bounds of the first if statement:
if (num > 6)
{
if (num < 12)
System.out.println("close!");
else
System.out.println("Sorry");
}
If we wanted the else to be associated with the first if, that can be accomplished with some well-placed curly braces:
if (num > 6)
{
if (num < 12)
System.out.println("close! ");
}
else
System.out.println("Sorry! ");
Some Sample Problems For each of the code segments shown below, give the output of that code if num is:
Problem 1
if (num <= 10)
{
if (num == 10)
System.out.println("exactly");
else
System.out.println("less");
}
else
System.out.println("greater");
Output when num is 5:
Output when num is 10:
Output when num is 17:
Problem 2
if (num <= 10)
{
if (num == 10)
System.out.println("exactly ");
}
else
System.out.println("bigger ");
Output when num is 5:
Output when num is 10:
Output when num is 17:
Problem 3
if (num <= 10)
if (num == 10)
System.out.println("exactly");
else
System.out.println("bigger");
Output when num is 5:
Output when num is 10:
Output when num is 17:
Order of evalution
Java will always check the left-hand operand for the || and && operators first. Furthermore, Java guarantees that it will not check the right hand operand if it already knows the value of the entire expression by only looking at the lefthand value.
num > 3 && num % 2 == 1
This is done so that statements like the following are possible (if the righthand term is evaluated a divide-by-zero error would occur):
if (num != 0 && 12/num == 2)
Conditional operator
The conditional operator is a trinary operator (i.e., an operator that has three operands). Its general form is:
(condition) ? value1 : value2
The entire expression has one of two values, either value1 or value2. If the condition before the '?' evaluates to true, then the expression has the value value1, otherwise it has the value value2.
It is often use use to condense several lines of an if-else statement. For example, the effect of the following four lines of code
if (players < 15)
teams = 1;
else
teams = 2;
can be accomplished with this one line of code:
teams = (players < 15) ? 1 : 2;
A Typical Use of the Conditional Operator
Suppose you have two values, x and y, and you want to put the biggest of these two values into the variable max. This could be accomplished with the following code:
if (x > y)
max = x;
else
max = y;
Or, you coud the same thing more compactly with:
max = (x > y) ? x : y;
A Few Practice Problems
Here a few short problems whose solutions require you to use selection. |