In programming, we use If Statements to allow our programs to.
make decisions. For example, a program might want to
ask the user if they're sure they want to exit a program, and if the user
says yes, the program terminates.
Or a program might ask the user to enter a user
name to view their order history. If
the user name is valid, the order entry screen is displayed.
If the name is not valid, an error message appears.
If statements can be single-sided, double-sided, or can be multi-sided.
We'll look at each of these and try some examples.
Single-sided ifs are used when you have an action you
want to perform when a specific condition is true, but
nothing to do when the condition is false.
A single sided If in Java has the general form:
if (relationalExpression) {
// code to execute if relationalExpression
// evaluates to true
}
The if-block (the code between the braces) only executes if the
relational expression evaluates to true. If there
is only one statement in the if-block, you can omit the braces. For
example, this is perfectly valid:
if (x > 3)
System.out.println("x is larger than 3");
However, this code below will not give the results you would expect:
if (x > 3)
System.out.println("x is larger");
System.out.println(" than 3);
In this example, the second print statement is not part of the
if-block and will be executed regardless of whether
or not x > 3 is true or false. To try this out, you can enter this
code segment into a new program and declare/initialize the variable x
to 5, then run the program. Then change x's value to 2 and run
the program.
For beginning programmers, or programmers new to a Java style of
syntax, I would get into the habit of leaving the braces on all the
time until you become comfortable with leaving them off. As you'll
see later on, leaving off the braces at the wrong time can cause
some serious logic errors.
Exercises
1. Write a program that asks the user for a number less
than 100. If the user's input is 100 or more,
display a message on the console.
2. Modify the program: Instead of checking to see if the
number is 100 or more, check to see if the number
is less than 100. If it is, calculate the square root of the number,
the square of the number, and the cube of the
number. Then display these on the console.
1.
2.
Double-Sided Ifs
A double-sided if has two actions: one to perform if the condition
is true, and one to perform if the condition
is false. The general form of the double-sided If statement is:
if (relationalExpression) {
// code to execute if relationalExpression
// evaluates to true
} else {
// code to execute if relationalExpression
// evaluates to false
}
Note that we still only have one condition, but now we have two
blocks of code. The if-block executes when the
condition is true, and the else-block executes when the condition
is false. Only one of the two blocks will execute!
As with the single-sided If, if you have only one code statement
in either the if-block or the else-block, you can
leave off the braces. For example, all of these are acceptable:
if (x > 3)
System.out.println("x is bigger than 3");
else
System.out.println("x is 3 or less");
...
if (x > 3) {
System.out.println("x is bigger");
System.out.println(" than 3");
} else
System.out.println("x is 3 or less");
...
if (x > 3)
System.out.println("x is bigger than 3");
else {
System.out.println("x is 3");
System.out.println(" or less");
}
Exercises
Write programs for each of the following:
Ask the user for a whole number. Display a message on the
screen that indicates whether the number is even or
odd.
The method Math.random() generates a random double
number greater than 0.0 and less than 1.0. Write a program
that simulates flipping a coin. Call the Math.random() method
and if the number generated is less than .5, display
"HEADS". Otherwise, display "TAILS".
Write a program that generates a random integer from 1 to 5. Then
ask the user to guess that number. If they guess correctly, display
the message, "You guessed correctly!". If they guess incorrectly,
display the message, "Sorry, you guessed incorrectly."
Write a program that simulates the tossing of two dice
(generate two random integers from 1 to 6). If doubles are rolled,
display a "You Win!!" message. Otherwise, tell the user what dice
values they rolled.
In a bank where you work, money is given an interest rate
of 7.5% if it is left in an account for more than 5
years; otherwise, the interest rate is 4.5%. Write a program
that asks the user for their current account balance, and number of years their
money has been sitting in the account. Then assign the
proper interest rate to a variable interestRate.
Finally, calculate and display the total interest for the current year
A program calculates a person's weekly pay based on the
following: If the hours worked are less than or equal
to 40, the person receives 10 dollars per hour; otherwise,
the person receives 10 dollars for the first 40 hours
and then 15 dollars for the hours they work over 40. Your
program should ask for the number of hours from the user,
and then calculate the weekly pay. Display your result.
Write a program that checks for a valid department number
entered by the user.
A department number is valid if it is between 1 and 45, inclusive.
Display messages stating whether or not the department number
is valid.
Modify the previous question: A valid department number is
between 1 and 45 inclusive, or greater than 200.
Modify the previous question: valid department numbers
include department 50, those between 1 and 45 inclusive, and those
that are greater than 200.
1.
2.
3.
4.
5.
6.
7.
8.
9.
Multi-Sided Ifs
Multiple-Sided Ifs are a set of if and else blocks that check
multiple conditions.
For example, you might want to check a variable to see if it
contained the number 1, the number 2, the number 3, or the number
4 and have a different action for each number.
The multi-sided if
will have four different conditions, and when it finds the
one condition that is true, that block is executed.
The general
form of a multi-sided if statement in Java is:
if (expression1) {
// execute this if expression1 is true
} else if (expression2) {
// execute this if expression2 is true
} else if (expression3) {
// execute this if expression3 is true
} else if (expression4) {
// execute this if expression4 is true
} else {
// execute this if none of the above are true
}
Here's a concrete example you can try:
if (number == 1 || number == 2) {
System.out.println("1, 2, Buckle my shoe");
} else if (number == 3 || number == 4) {
System.out.println("3, 4, Close the door");
} else if (number == 5 || number == 6) {
System.out.println("5, 6, Pick up sticks");
} else if (number == 7 || number == 8) {
System.out.println("7, 8, Don't be late!");
} else {
System.out.println("I don't know any more...");
}
You can have as many relational expressions as you
need in this kind of structure. Notice the single else-block
at the bottom: this block is optional and can be used
if you want code to execute when none of the conditions applies.
As with the other structures, you can eliminate the
braces if there is only one statement in a block. For
example, this is also valid:
if (number == 1 || number == 2)
System.out.println("1, 2, Buckle my shoe");
else if (number == 3 || number == 4)
System.out.println("3, 4, Close the door");
else if (number == 5 || number == 6)
System.out.println("5, 6, Pick up sticks");
else if (number == 7 || number == 8)
System.out.println("7, 8, Don't be late!");
else
System.out.println("I don't know any more...");
Exercises
The following program determines and displays
the letter grade for a student's final grade:
import java.util.Scanner;
public class GetLetterGrade {
public static void main(String[] args) {
Scanner keysIn = new Scanner(System.in);
System.out.print("Enter the final grade: ");
double grade = keysIn.nextDouble();
String letter = "";
if (grade < 50) {
letter = "F";
} else if (grade >= 50) {
letter = "D";
} else if (grade >= 60) {
letter = "C";
} else if (grade >= 65) {
letter = "C+";
} else if (grade >= 70) {
letter = "B";
} else if (grade >= 75) {
letter = "B+";
} else if (grade >= 80) {
letter = "A";
} else if (grade >= 90) {
letter = "A+";
}
System.out.println("Letter grade: " + letter);
}
}
What would the output be if the user entered a final grade of 48?
What would the output be if the user entered a final grade of 55?
What would the output be if the user entered a final grade of 85?
Why doesn't this program do what it's supposed to do?
How would you rewrite it correctly?
2. Write a Java program that calculates and displays
the interest rate for funds that are left on deposit for a
certain amount of time. The interest rate is determined by
the following chart:
Years on Deposit
Rate
5 years or more
4.75%
4 years or more, but less than 5 years
4.5%
3 years or more, but less than 4 years
4%
2 years or more, but less than 3 years
3.5%
1 year or more, but less than 2 years
3%
less than 1 year
2.5%
A program needs to display the amount of commission
paid to sales people. Commission paid is equal to the amount
of sales multiplied by the commission rate. Commission rates
are assigned according to the following chart:
Sales Amount
Commission Rate
under $1000
5%
$1000 or more but less than $2000
7.5%
$2000 or more, but less than $3500
10%
$3500 or more
15%
1. a. What would the output be if the user entered
a final grade of 48?
F
1. b. What would the output be if the user entered
a final grade of 55?
D
1. c. What would the output be if the user entered
a final grade of 85?
D
1. d. Why doesn't this program do what it's supposed to do?
How would you rewrite it correctly?
It doesn't work because the range check
is not done properly. Since you're starting from the bottom and going up to higher
values, you should be comparing grade to the highest value in each range.