|
Conditional Statements |
|
|
A conditional statement is an expression that produces a
true or false result. You can use that result as you see fit. To create the
expression, you use the Boolean operators we studied in the previous lesson. In
the previous lesson, we saw only how to perform the operations and how to get
the results, not how to use them. To use the result of a Boolean operation, the Java
programming language provides some specific conditional operators.
|
Practical
Learning: Introducing Conditional Statements |
|
- Start NetBeans and create a Java Application named bcr1
- Change the file as follows:
package bcr1;
import java.util.Scanner;
public class Main {
static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
long employeeNumber;
double hourlySalary;
double weeklyTime;
double weeklySalary;
System.out.print("Enter Employee Number: ");
employeeNumber = scnr.nextLong();
System.out.print("Enter Hourly Salary: ");
hourlySalary = scnr.nextDouble();
System.out.print("Enter Weekly Time: ");
weeklyTime = scnr.nextDouble();
weeklySalary = hourlySalary * weeklyTime;
System.err.println("Employee Name: " + employeeNumber);
System.err.println("Hourly Salary: " + hourlySalary);
System.err.println("Weekly Time: " + weeklyTime);
System.err.println("Weekly Salary: " + employeeNumber);
}
}
|
- To execute the exercise, press F6
- Enter the Employee number as 82500, the hourly salary as 22.35,
and the weekly hours as 38, then press Enter
Enter Employee Number:
82500
Enter Hourly Salary:
22.35
Enter Weekly Time:
38
Employee Name: 82500
Hourly Salary: 22.35
Weekly Time: 38.0
Weekly Salary: 82500
|
Consider the following program:
import java.util.Scanner;
public class Exercise {
static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String houseType = "Unknown";
int choice = 0;
System.out.println("Enter the type of house you want to purchase");
System.out.println("1. Single Family");
System.out.println("2. Townhouse");
System.out.println("3. Condominium");
System.out.print("You Choice? ");
choice = scnr.nextInt();
System.out.println("Desired House Type: " + houseType);
}
}
Here is an example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 2
Desired House Type: Unknown
To check if an expression is true and use its Boolean
result, you can use the if operator. Its formula is:
if(Condition) Statement;
The Condition can be the type of Boolean operation we
studied in the previous lesson. That is, it can have the following formula:
Operand1 BooleanOperator Operand2
If the Condition produces a true result, then the
compiler executes the Statement. If the statement to execute is short,
you can write it on the same line with the condition that is being checked. Here
is an example:
import java.util.Scanner;
public class Exercise {
static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String houseType = "Unknown";
int choice = 0;
System.out.println("Enter the type of house you want to purchase");
System.out.println("1. Single Family");
System.out.println("2. Townhouse");
System.out.println("3. Condominium");
System.out.print("You Choice? ");
choice = scnr.nextInt();
if (choice == 1) houseType = "Single Family";
System.out.println("Desired House Type: " + houseType);
}
}
Here is an example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
Desired House Type: Single Family
If the Statement is too long, you can write it on a
different line than the if condition. Here is an example:
import java.util.Scanner;
public class Exercise {
static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String houseType = "Unknown";
int choice = 0;
System.out.println("Enter the type of house you want to purchase");
System.out.println("1. Single Family");
System.out.println("2. Townhouse");
System.out.println("3. Condominium");
System.out.print("You Choice? ");
choice = scnr.nextInt();
if (choice == 1)
houseType = "Single Family";
System.out.println("Desired House Type: " + houseType);
}
}
You can also write the Statement on its own line even
if the statement is short enough to fit on the same line with the Condition.
Although the (simple) if statement is used to check
one condition, it can lead to executing multiple dependent statements. If that
is the case, enclose the group of statements between an opening curly bracket
“{“ and a closing curly bracket “}”. Here is an example:
import java.util.Scanner;
public class Exercise {
static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String houseType = "Unknown";
int choice = 0;
System.out.println("Enter the type of house you want to purchase");
System.out.println("1. Single Family");
System.out.println("2. Townhouse");
System.out.println("3. Condominium");
System.out.print("Your Choice? ");
choice = scnr.nextInt();
if (choice == 1) {
houseType = "Single Family";
System.out.println("Desired House Type: " + houseType);
}
}
}
If you omit the brackets, only the statement that
immediately follows the condition would be executed.
Just as you can write one if condition, you can write
more than one. Here are examples:
import java.util.Scanner;
public class Exercise {
static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String houseType = "Unknown";
int choice = 0;
System.out.println("Enter the type of house you want to purchase");
System.out.println("1. Single Family");
System.out.println("2. Townhouse");
System.out.println("3. Condominium");
System.out.print("Your Choice? ");
choice = scnr.nextInt();
if (choice == 1)
houseType = "Single Family";
if (choice == 2)
houseType = "Townhouse";
if (choice == 3)
houseType = "Condominium";
System.out.println("Desired House Type: " + houseType);
}
}
Here is an example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 3
Desired House Type: Condominium
Practical
Learning: Using an if Statement |
|
- To use an if condition, change the document as follows:
package bcr1;
import java.util.Scanner;
public class Main {
static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
long employeeNumber;
double hourlySalary;
double weeklyTime;
double weeklySalary;
System.out.print("Enter Employee Number: ");
employeeNumber = scnr.nextLong();
System.out.print("Enter Hourly Salary: ");
hourlySalary = scnr.nextDouble();
System.out.print("Enter Weekly Time: ");
weeklyTime = scnr.nextDouble();
weeklySalary = hourlySalary * weeklyTime;
System.err.println("Employee Name: " + employeeNumber);
System.out.println("Hourly Salary: " + hourlySalary);
System.out.println("Weekly Time: " + weeklyTime);
System.out.println("Weekly Salary: " + employeeNumber);
if( weeklyTime > 40 ) {
System.out.println("You got overtime");
System.out.println("Management does not like paying overtime");
System.out.println("If you overtime again, you will get in trouble");
}
}
}
|
- To execute the exercise, press F6
- Enter the Employee number as 82500, the hourly salary as 22.35,
and the weekly hours as 36.50, then press Enter
Enter Employee Number: 82500
Enter Hourly Salary: 22.35
Enter Weekly Time: 36.50
Employee Name: 82500
Hourly Salary: 22.35
Weekly Time: 36.5
Weekly Salary: 82500
|
- Execute the application again
- Enter the Employee number as 82500, the hourly salary as 22.35,
and the weekly hours as 40, then press Enter
Enter Employee Number: 82500
Enter Hourly Salary: 22.35
Enter Weekly Time: 40
Employee Name: 82500
Hourly Salary: 22.35
Weekly Time: 40.0
Weekly Salary: 82500
|
- Execute the application again
- Enter the Employee number as 82500, the hourly salary as 22.35,
and the weekly hours as 42.50, then press Enter
Enter Employee Number: 82500
Enter Hourly Salary: 22.35
Enter Weekly Time: 42.50
Employee Name: 82500
Hourly Salary: 22.35
Weekly Time: 42.5
Weekly Salary: 82500
You got overtime
Management does not like paying overtime
If you overtime again, you will get in trouble
|
- Close the message box and the DOS window then return to your programming
environment
Here is an example of what we learned in the
previous section:
import java.util.Scanner;
public class Exercise {
static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String houseType = "Unknown";
int choice = 0;
System.out.println("Enter the type of house you want to purchase");
System.out.println("1. Single Family");
System.out.println("2. Townhouse");
System.out.println("3. Condominium");
System.out.print("Your Choice? ");
choice = scnr.nextInt();
if (choice == 1)
houseType = "Single Family";
if (choice == 2)
houseType = "Townhouse";
if (choice == 3)
houseType = "Condominium";
System.out.println("Desired House Type: " + houseType);
if (houseType == "Single Family")
System.out.println("Desired House Matched");
}
}
If you use an if condition to perform an operation
and if the result is true, we saw that you could execute the statement. As we
saw in the previous section, any other result would be ignored. To address an
alternative to an if condition, you can use the else condition.
The formula to follow is:
if(Condition)
Statement1;
else
Statement2;
Once again, the Condition can be a Boolean operation
like those we studied in the previous lesson. If the Condition is true,
then the compiler would execute Statement1. If the Condition is
false, then the compiler would execute Statement2. Here is an example:
import java.util.Scanner;
public class Exercise {
static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String houseType = "Unknown";
int choice = 0;
System.out.println("Enter the type of house you want to purchase");
System.out.println("1. Single Family");
System.out.println("2. Townhouse");
System.out.println("3. Condominium");
System.out.print("Your Choice? ");
choice = scnr.nextInt();
if (choice == 1)
houseType = "Single Family";
if (choice == 2)
houseType = "Townhouse";
if (choice == 3)
houseType = "Condominium";
System.out.println("Desired House Type: " + houseType);
if (houseType == "Single Family")
System.out.println("Desired House Matched");
else
System.out.println("No House Desired");
}
}
Here is an example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
Desired House Type: SingleFamily
Desired House Matched
Here is another example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 2
Desired House Type: Townhouse
No House Desired
Practical
Learning: Using if...Else |
|
- To use the else clause, make the following changes to the file:
package bcr1;
import java.util.Scanner;
public class Main {
static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
long employeeNumber;
double hourlySalary;
double weeklyTime, regularTime, overtime;
double regularPay, overtimePay, netPay;
System.out.print("Enter Employee Number: ");
employeeNumber = scnr.nextLong();
System.out.print("Enter Hourly Salary: ");
hourlySalary = scnr.nextDouble();
System.out.print("Enter Weekly Time: ");
weeklyTime = scnr.nextDouble();
if(weeklyTime < 40 ) {
regularTime = weeklyTime;
overtime = 0;
regularPay = hourlySalary * regularTime;
overtimePay = 0;
netPay = regularPay;
}
else {
regularTime = 40;
overtime = weeklyTime - 40;
regularPay = hourlySalary * 40;
overtimePay = hourlySalary * overtime;
netPay = regularPay + overtimePay;
}
System.out.println("==============================");
System.out.println("=//= BETHESDA CAR RENTAL =//=");
System.out.println("==-=-= Employee Payroll =-=-==");
System.out.println("------------------------------");
System.out.println("Employee #: " + employeeNumber);
System.out.println("Hourly Salary: " + hourlySalary);
System.out.println("Weekly Time: " + weeklyTime);
System.out.println("Weekly Salary: " + employeeNumber);
System.out.println("Regular Pay: " + regularPay);
System.out.println("Overtime Pay: " + overtimePay);
System.out.println("Total Pay: " + netPay);
System.out.println("==============================");
}
}
|
- Execute the application
- Enter the Employee name as 82500, the hourly salary as 22.35,
and the weekly time as 42.50
- Press Enter:
Enter Employee Number: 50700
Enter Hourly Salary: 22.35
Enter Weekly Time: 42.50
==============================
=//= BETHESDA CAR RENTAL =//=
==-=-= Employee Payroll =-=-==
------------------------------
Employee #: 50700
Hourly Salary: 22.35
Weekly Time: 42.5
Weekly Salary: 50700
Regular Pay:894.0
Overtime Pay:55.875
Total Pay:949.875
==============================
|
The Ternary Operator (?:) |
|
The conditional operator behaves like a simple if…else statement. Its syntax is:
Condition ? Statement1 : Statement2;
The compiler would first test the Condition. If the
Condition is true, then it would execute Statement1, otherwise it would execute
Statement2. When you request two numbers from the user and would like to compare them, the following program would do
find out which one of both numbers is higher. The comparison is performed
using the conditional operator:
import java.util.Scanner;
public class Exercise {
static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int number1 = 0;
int number2 = 0;
int maximum = 0;
System.out.print("Enter first numbers: ");
number1 = scnr.nextInt();
System.out.print("Enter second numbers: ");
number2 = scnr.nextInt();
maximum = (number1 < number2) ? number2 : number1;
System.out.print("The maximum of ");
System.out.print(number1);
System.out.print(" and ");
System.out.print(number2);
System.out.print(" is ");
System.out.println(maximum);
}
}
Here is an example of running the program;
Enter first numbers: 244
Enter second numbers: 68
The maximum of 244 and 68 is 244
if…else if and if…else
if…else
|
|
If you use an if...else conditional
statement, you can process only two statements. In some cases, you may
deal with more than two conditions. In this case, you can use an if...else
if condition. Its formula is:
if(Condition1) Statement1;
else if(Condition2) Statement2;
The compiler would first check Condition1. If
Condition1 is true, then Statement1 would be executed. If Condition1
is false, then the compiler would check Condition2. If Condition2
is true, then the compiler would execute Statement2. Any other result
would be ignored. Here is an example:
import java.util.Scanner;
enum HouseType {
UNKNOWN,
SINGLEFAMILY,
TOWNHOUSE,
CONDOMINIUM
}
public class Exercise {
static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
HouseType Type = HouseType.UNKNOWN;
int Choice = 0;
String Garage = "";
System.out.println("Enter the type of house you want to purchase");
System.out.println("1. Single Family");
System.out.println("2. Townhouse");
System.out.println("3. Condominium");
System.out.print("You Choice? ");
Choice = scnr.nextInt();
if (Choice == 1) Type = HouseType.SINGLEFAMILY;
else if (Choice == 2) Type = HouseType.TOWNHOUSE;
System.out.print("Does the house have an indoor garage (1=Yes/0=No)? ");
int Answer = scnr.nextInt();
if (Answer == 1)
Garage = "Yes";
else
Garage = "No";
System.out.println("\nDesired House Type: " + Type);
System.out.println("Has indoor garage? " + Garage);
}
}
Here is an example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
Does the house have an indoor garage (1=Yes/0=No)? 1
Desired House Type: SINGLEFAMILY
Has indoor garage? Yes
Here is another example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 2
Does the house have an indoor garage (1=Yes/0=No)? 6
Desired House Type: TOWNHOUSE
Has indoor garage? No
Notice that only two conditions are evaluated. Any
condition other than these two is not considered. Because there can be
other alternatives, the Java language provides an alternate else as the
last resort. Its formula is:
if(Condition1)
Statement1;
else if(Condition2)
Statement2;
else
Statement-n;
|
|
|
if(Condition1)
Statement1;
else if(Condition2)
Statement2;
else if(Condition3)
Statement3;
else
Statement-n;
|
The compiler will check the first condition. If
Condition1 is true, it executes Statement1. If Condition1 is false,
then the compiler will check the second condition. If Condition2 is
true, it will execute Statement2. When the compiler finds a Condition-n
to be true, it will execute its corresponding statement. It that Condition-n is false, the compiler will check the subsequent condition.
This means you can include as many conditions as you see fit using the
else if statement. If after examining all the known possible conditions
you still think that there might be an unexpected condition, you can use
the optional single else. Here is an example:
import java.util.Scanner;
enum HouseType {
UNKNOWN,
SINGLEFAMILY,
TOWNHOUSE,
CONDOMINIUM
}
public class Exercise {
static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
HouseType Type = HouseType.UNKNOWN;
int Choice = 0;
String Garage = "";
System.out.println("Enter the type of house you want to purchase");
System.out.println("1. Single Family");
System.out.println("2. Townhouse");
System.out.println("3. Condominium");
System.out.print("You Choice? ");
Choice = scnr.nextInt();
if (Choice == 1)
Type = HouseType.SINGLEFAMILY;
else if (Choice == 2)
Type = HouseType.TOWNHOUSE;
else if (Choice == 3)
Type = HouseType.CONDOMINIUM;
else
Type = HouseType.UNKNOWN;
System.out.print("Does the house have an indoor garage (1=Yes/0=No)? ");
int Answer = scnr.nextInt();
if (Answer == 1)
Garage = "Yes";
else
Garage = "No";
System.out.println("\nDesired House Type: " + Type);
System.out.println("Has indoor garage? " + Garage);
}
}
Here is an example of running the program:
Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 3
Does the house have an indoor garage (1=Yes/0=No)? 0
Desired House Type: CONDOMINIUM
Has indoor garage? No
Practical Learning:
Using an if…else
if…else Statement |
|
- Change the Main.java file as follows:
package bcr1;
import java.util.Scanner;
public class Main {
static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
long employeeNumber;
String employeeName;
double hourlySalary;
double weeklyTime, regularTime, overtime;
double regularPay, overtimePay, netPay;
System.out.print("Enter Employee Number (00000): ");
employeeNumber = scnr.nextLong();
if( employeeNumber == 82500 )
employeeName = "Helene Mukoko";
else if( employeeNumber == 92746 )
employeeName = "Raymond Kouma";
else if( employeeNumber == 54080 )
employeeName = "Henry Larson";
else if( employeeNumber == 86285 )
employeeName = "Gertrude Monay";
else
employeeName = "Unknown";
System.out.print("Enter Hourly Salary: ");
hourlySalary = scnr.nextDouble();
System.out.print("Enter Weekly Time: ");
weeklyTime = scnr.nextDouble();
if(weeklyTime < 40 ) {
regularTime = weeklyTime;
overtime = 0;
regularPay = hourlySalary * regularTime;
overtimePay = 0;
netPay = regularPay;
}
else {
regularTime = 40;
overtime = weeklyTime - 40;
regularPay = hourlySalary * 40;
overtimePay = hourlySalary * overtime;
netPay = regularPay + overtimePay;
}
System.out.println("======================");
System.out.println("=//= BETHESDA CAR RENTAL =//=");
System.out.println("==-=-= Employee Payroll =-=-==");
System.out.println("-------------------------------------------");
System.out.println("Employee #: " + employeeNumber);
System.out.println("Employee Name: " + employeeName);
System.out.println("Hourly Salary: " + hourlySalary);
System.out.println("Weekly Time: " + weeklyTime);
System.out.println("Weekly Salary: " + employeeNumber);
System.out.println("Regular Pay: " + regularPay);
System.out.println("Overtime Pay: " + overtimePay);
System.out.println("Total Pay: " + netPay);
System.out.println("======================");
}
}
|
- To execute the exercise, press F6
- Enter the Employee number as 54080, the hourly salary as 20.60,
and the weekly hours as 36.50, then press Enter
Enter Employee Number (00000): 54080
Enter Hourly Salary: 20.60
Enter Weekly Time: 36.50
==============================
=//= BETHESDA CAR RENTAL =//=
==-=-= Employee Payroll =-=-==
-------------------------------------------
Employee #: 54080
Employee Name: Henry Larson
Hourly Salary: 20.6
Weekly Time: 36.5
Weekly Salary: 54080
Regular Pay: 751.9000000000001
Overtime Pay: 0.0
Total Pay: 751.9000000000001
==============================
|
- Execute the application again
- Enter the Employee number as 82500, the hourly salary as 22.35,
and the weekly hours as 42.50, then press Enter
- Execute the application again
- Enter the Employee number as 86285, the hourly salary as 35.70,
and the weekly hours as 40.00, then press Enter
|