Home

Looping and Compounding Statements

 

Conditional Looping

 

Introduction

A loop is a type of conditional statement that keeps checking a condition and executing a statement until the condition is false.

 

while a Condition is True

One of the operators used to perform a loop is called while. Its formula is:

while(Condition) Statement;

To execute this expression, the compiler first examines the Condition. If the Condition is true, then it executes the Statement. After executing the Statement, the Condition is checked again. AS LONG AS the Condition is true, it will keep executing the Statement. When or once the Condition becomes false, it exits the loop:

While

Here is an example:

public class Exercise {
    static void main(String[] args) {
        int Stories = 0;
	
        while( stories <= 4 ) {
            System.out.println("Number " + stories);
            stories++;
        }
    }
}

This would produce:

Number 0
Number 1
Number 2
Number 3
Number 4

To effectively execute a while condition, you should make sure you provide a mechanism for the compiler to use or get a reference value for the condition, variable, or expression being checked. This is sometimes in the form of a variable being initialized although it could be some other expression. Such a while condition could be illustrated as follows:

Flowchart: While

do This while a Condition is True

The while loop is used first check a condition and then execute a statement. If the condition is false, the statement would never execute. Consider the following program:

public class Exercise {
    static void main(String[] args) {
        int Stories = 5;

        while (stories <= 4) {
            System.out.println("Number " + stories);
            stories++;
        }
    }
}

When this program executes, nothing from the while loop would execute because, as the condition is checked in the beginning, it is false and the compiler would not get to the Statement. In some cases, you may want to execute a statement before checking the condition for the first time. This can be done using the do…while statement. Its formula is:

do Statement while (Condition);

The do…while condition executes a Statement first. After the first execution of the Statement, it examines the Condition. If the Condition is true, then it executes the Statement again. It will keep executing the Statement AS LONG AS the Condition is true. Once the Condition becomes false, the looping (the execution of the Statement) would stop.

If the Statement is a short one, such as made of one line, simply write it after the do keyword. Like the if and the while statements, the Condition being checked must be included between parentheses. The whole do…while statement must end with a semicolon.

do...while

Another version of the counting program seen previously would be:

public class Exercise {
    static void main(String[] args) {
        int Stories = 0;

        do
            System.out.println("Number " + stories++);
        while (stories <= 4);
    }
}

This would produce:

Number 0
Number 1
Number 2
Number 3
Number 4

If the Statement is long and should span more than one line, start it with an opening curly bracket "{" and end it with a closing curly bracket "}".

for

The for statement is typically used to count a number of items. At its regular structure, it is divided in three parts. The first section specifies the starting point for the count. The second section sets the counting limit. The last section determines the counting frequency. The syntax of the for statement is:

for(Start; End; Frequency) Statement;

The Start expression is a variable assigned the starting value. This could be Count = 0;

The End expression sets the criteria for ending the counting. An example would be Count < 24; this means the counting would continue as long as the Count variable is less than 24. When the count is about to rich 24, because in this case 24 is excluded, the counting would stop. To include the counting limit, use the <= or >= comparison operators depending on how you are counting.

The Frequency expression would let the compiler know how many numbers to add or subtract before continuing with the loop. This expression could be an increment operation such as ++Count.

Here is an example that applies the for statement:

public class Exercise {

    static void main(String[] args) {
        for (int Stories = 0; stories <= 4; stories++)
            System.out.println("Number " + stories);
    }
}

This would produce:

Number 1
Number 2
Number 3
Number 4 

Logical Conjunction: AND

 

Introduction

Imagine that a real estate agent who will be using your program is meeting with a potential buyer and asking questions from 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;
        double value = 0D;

        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";
        if (choice == 2)
            houseType = "Townhouse";
        if (choice == 3)
            houseType = "Condominium";

        System.out.print("Up to how much can you afford? $");
        value = scnr.nextDouble();

        System.out.println("Desired House Type:     " + houseType);
        System.out.println("Maximum value afforded: " + value);
   }
}

Suppose a customer responds to these questions: she indicates that she wants single family house but she cannot afford more than $550,000:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
Up to how much can you afford? $550000

Desired House Type:      SingleFamily
Maximum value afforded:  $550,000.00

When considering a house for this customer, there are two details to be validated here: the house must be a single family home, second, it must cost less than $550,001. We can create two statements as follows:

  1. The house is single family
  2. The house costs less than $550,000

From our list of real estate properties, if we find a house that is a single family home, we put it in our list of considered properties:

Type of House House
The house is single family True

On the other hand, if we find a house that is less than or equal to $550,000, we retain it:

Price Range Value
$550,000 True

One of the ways you can combine two comparisons is by joining them. For our customer, we want a house to meet BOTH criteria. If the house is a town house, based on the request of our customer, its conditional value is false. If the house is more than $550,000, the value of the Boolean Value is true. The Boolean operator used to join two criteria is called AND. This can be illustrated as follows:

Type of House House Value Result
Town House $625,000 Town House AND $625,000
False False False

In Java, the Boolean AND operator is performed using the && operator. 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;
        double value = 0D;

        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";
        if (choice == 2)
            houseType = "Townhouse";
        if (choice == 3)
            houseType = "Condominium";

        System.out.print("Up to how much can you afford? $");
        value = scnr.nextDouble();

        System.out.println("Desired House Type:     " + houseType);
        System.out.println("Maximum value afforded: " + value);

        if (houseType == "Single Family" && value <= 550000)
            System.out.println("Desired House Matched");
   }
}

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
Up to how much can you afford? $450000

Desired House Type:      SingleFamily
Maximum value afforded:  $450,000.00

Desired House Matched

By definition, a logical conjunction combines two conditions. To make the program easier to read, each side of the conditions can be included in parentheses. 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;
        double value = 0D;

        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";
        if (choice == 2)
            houseType = "Townhouse";
        if (choice == 3)
            houseType = "Condominium";

        System.out.print("Up to how much can you afford? $");
        value = scnr.nextDouble();

        System.out.println("Desired House Type:     " + houseType);
        System.out.println("Maximum value afforded: " + value);

        if( (houseType == "Single Family") && (value <= 550000) )
            System.out.println("Desired House Matched");
   }
}

Suppose we find a single family home. The first condition is true for our customer. With the AND Boolean operator, if the first condition is true, then we consider the second criterion. Suppose that the house we are considering costs $750,500: the price is out of the customer's range. Therefore, the second condition is false. In the AND Boolean algebra, if the second condition is false, even if the first is true, the whole condition is false. This would produce the following table:

Type of House House Value Result
Single Family $750,500 Single Family AND $750,500
True False False

This can be illustrated by the following run of the 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;
        double value = 0D;

        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";
        if (choice == 2)
            houseType = "Townhouse";
        if (choice == 3)
            houseType = "Condominium";

        System.out.print("Up to how much can you afford? $");
        value = scnr.nextDouble();

        System.out.println("Desired House Type:     " + houseType);
        System.out.println("Maximum value afforded: " + value);

        if( (houseType == "Single Family") && (value <= 550000) )
            System.out.println("Desired House Matched");
        else
            System.out.println("The House Doesn't Match the Desired Criteria");
   }
}

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
Up to how much can you afford? $750000

Desired House Type:      SingleFamily
Maximum value afforded:  $750,000.00

The House Doesn't Match the Desired Criteria

Suppose we find a townhouse that costs $420,000. Although the second condition is true, the first is false. In Boolean algebra, an AND operation is false if either condition is false:

Type of House House Value Result
Town House $420,000 Town House AND $420,000
False True False

Here is an example of running the above program:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 2
Up to how much can you afford? $420000

Desired House Type:      Townhouse
Maximum value afforded:  $420,000.00

The House Doesn't Match the Desired Criteria

If we find a single family home that costs $345,000, both conditions are true. In Boolean algebra, an AND operation is true if BOTH conditions are true. This can be illustrated as follows:

Type of House House Value Result
Single Family $345,000 Single Family AND $345,000
True True True

This can be revealed in the following run of the above program:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
Up to how much can you afford? $345000

Desired House Type:      SingleFamily
Maximum value afforded:  $345,000.00

Desired House Matched

These four tables can be resumed as follows:

If Condition1 is If Condition2 is Condition1
AND
Condition2
False False False
False True False
True False False
True True True

As you can see, a logical conjunction is true only of BOTH conditions are true.

Combining Conjunctions

As seen above, the logical conjunction operator is used to combine two conditions. In some cases, you will need to combine more than two conditions. Imagine a customer wants to purchase a single family house that costs up to $450,000 with an indoor garage. This means that the house must fulfill these three requirements:

  1. The house is a single family home
  2. The house costs less than $450,001
  3. The house has an indoor garage

Here the program that could be used to check these conditions:

import java.util.Scanner;
        
public class Exercise {
    static void main(String[] args) {        
	Scanner scnr = new Scanner(System.in);
        int choice = 0;
        double value = 0D;
        String houseType = "Unknown";
        boolean hasIndoorGarage = false;

        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";
        if (choice == 2)
            houseType = "Townhouse";
        if (choice == 3)
            houseType = "Condominium";

        System.out.print("Up to how much can you afford? $");
        value = scnr.nextDouble();

        System.out.print("Does the house have an indoor garage (1=Yes/0=No)? ");
        int ans = scnr.nextInt();

        System.out.println("Desired House Type:     " + houseType);
        System.out.println("Maximum value afforded: " + value);
        System.out.print("House has indoor garage: ");
        if (ans == 1)
            System.out.println("Yes");
        else
            System.out.println("No");

        if ((houseType == "Single Family") && (value <= 550000) && (ans == 1))
            System.out.println("Desired House Matched");
        else
            System.out.println("The House Doesn't Match the Desired Criteria");
   }
}

We saw that when two conditions are combined, the compiler first checks the first condition, followed by the second. In the same way, if three conditions need to be considered, the compiler evaluates the truthfulness of the first condition:

Type of House
A
Town House
False

If the first condition (or any condition) is false, the whole condition is false, regardless of the outcome of the other(s). If the first condition is true, then the second condition is evaluated for its truthfulness:

Type of House Property Value
A B
Single Family $655,000
True False

If the second condition is false, the whole combination is considered false:

A B A && B
True False False

When evaluating three conditions, if either the first or the second is false, since the whole condition would become false, there is no reason to evaluate the third. If both the first and the second conditions are false, there is also no reason to evaluate the third condition. Only if the first two conditions are true will the third condition be evaluated whether it is true:

Type of House Property Value Indoor Garage
A B C
Single Family $425,650 None
True True False

The combination of these conditions in a logical conjunction can be written as A && B && C. If the third condition is false, the whole combination is considered false:

A B A && B C A && B && C
True True True False False

To verify this, 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
Up to how much can you afford? $425000
Does the house have an indoor garage (1=Yes/0=No)? 0

Desired House Type:      SingleFamily
Maximum value afforded:  $425,000.00
House has indoor garage: No

The House Doesn't Match the Desired Criteria

From our discussion so far, the truth table of the combinations can be illustrated as follows:

A B C A && B && C
False Don't Care Don't Care False
True False Don't Care False
True True False False

The whole combination is true only if all three conditions are true. This can be illustrated as follows:

A B C A && B && C
False False False False
False False True False
True False False False
True False True False
False True False False
False True True False
True True False False
True True True True

 
 

Logical Disjunction: OR

 

Introduction

Our real estate company has single family homes, townhouses, and condominiums. All of the condos have only one level, also referred to as a story. Some of the single family homes have one story, some have two and some others have three levels. All townhouses have three levels.

Another customer wants to buy a home. The customer says that he primarily wants a condo, but if our real estate company doesn't have a condominium, that is, if the company has only houses, whatever it is, whether a house or a condo, it must have only one level (story) (due to an illness, the customer would not climb the stairs). When considering the properties of our company, we would proceed with these statements:

  1. The property is a condominium
  2. The property has one story

If we find a condo, since all of our condos have only one level, the criterion set by the customer is true. Even if we were considering another (type of) property, it wouldn't matter. This can be resumed in the following table:

Type of House House
Condominium True

The other properties would not be considered, especially if they have more than one story:

Number of Stories Value
3 False

To check for either of two conditions, in Boolean algebra, you can use an operator called OR. We can show this operation as follows:

Condominium One Story Condominium OR 1 Story
True False True

In Boolean algebra, this type of comparison is performed using the OR operator. In Java, the OR operator is performed using the || operator. 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;
        int stories = 1;

        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";
        if (choice == 2)
            houseType = "Townhouse";
        if (choice == 3)
            houseType = "Condominium";

        System.out.print("How many stories? ");
        stories = scnr.nextInt();

        System.out.println("Desired House Type: " + houseType);
        System.out.println("Number of Stories:  " + stories);

        if( (houseType == "Condominium") || (stories == 1) )
            System.out.println("Desired House Matched");
        else
            System.out.println("The House Doesn't Match the Desired Criteria");
   }
}

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
How many stories? 6

Desired House Type: Condominium
Number of Stories:  6

Desired House Matched

Suppose that, among the properties our real estate company has available, there is no condominium. In this case, we would then consider the other properties:

Type of House House
Single Family False

If we have a few single family homes, we would look for one that has only one story. Once we find one, our second criterion becomes true:

Type of House One Story Condominium OR 1 Story
False True True

This can be illustrated in the following run of the above program:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 1
How many stories? 1

Desired House Type: SingleFamily
Number of Stories:  1

Desired House Matched

If we find a condo and it is one story, both criteria are true. This can be illustrated in the following table:

Type of House One Story Condominium OR 1 Story
False True True
True True True

The following run of the program demonstrates this:

Enter the type of house you want to purchase
1. Single Family
2. Townhouse
3. Condominium
You Choice? 3
How many stories? 1

Desired House Type: Condominium
Number of Stories:  1

Desired House Matched

A Boolean OR operation produces a false result only if BOTH conditions ARE FALSE:

If Condition1 is If Condition2 is Condition1 OR Condition2
False True True
True False True
True True True
False False False

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
How many stories? 2

Desired House Type: Townhouse
Number of Stories:  2

The House Doesn't Match the Desired Criteria

Combinations of Disjunctions

As opposed to evaluating only two conditions, you may face a situation that presents three of them and must consider a combination of more than two conditions. 

Controlling the Conditional Statements

 

Introduction

Computer programming presents you with various options to manage the flow of processing an application. You can nest a condition in another. You can ask the compiler to skip a processing for any reason you judge necessary. Or, you can control how a method would return, if any.

Practical LearningPractical Learning: Controlling the Conditional Statements

  1. Start NetBeans and create a Java Application named bcr2
  2. Change the file as follows:
    package bcr2;
    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.printf("Employee #:    %d\n", employeeNumber);
            System.out.printf("Employee Name: %s\n", employeeName);
            System.out.printf("Hourly Salary: %.2f\n", hourlySalary);
            System.out.printf("Weekly Time:   %.2f\n", weeklyTime);
            System.out.printf("Regular Pay:   %.2f\n", regularPay);
            System.out.printf("Overtime Pay:  %.2f\n", overtimePay);
            System.out.printf("Total Pay:     %.2f\n", netPay);
            System.out.println("======================");
        }
    }
  3. To execute the exercise, press F6
  4. Enter the Employee number as 82500, the hourly salary as 22.35, and the weekly hours as 38.50, then press Enter
    Enter Employee Number (00000): 82500
    Enter Hourly Salary: 22.35
    Enter Weekly Time: 38.50
    ==============================
    =//= BETHESDA CAR RENTAL =//=
    ==-=-= Employee Payroll =-=-==
    ------------------------------
    Employee #:    82500
    Employee Name: Helene Mukoko
    Hourly Salary: 22.35
    Weekly Time:   38.50
    Regular Pay:   860.48
    Overtime Pay:  0.00
    Total Pay:     860.48
    ======================

Nesting a Conditional Statement

Consider the following program:

import java.util.Scanner;
        
public class Exercise {
    static void main(String[] args) {        
	Scanner scnr = new Scanner(System.in);
        int typeOfHome = 0;

        do {
            System.out.println("What Type of House Would you Like to Purchase?");
            System.out.println("1 - Single Family");
            System.out.println("2 - Town House");
            System.out.println("3 - Condominium");
            System.out.print("Your Choice? ");
            typeOfHome = scnr.nextInt();
        } while ((typeOfHome < 1) || (typeOfHome > 3));

        if (typeOfHome == 1)
            System.out.println("\nType of Home: Single Family");
        else if (typeOfHome == 2)
            System.out.println("\nType of Home: Town House");
        else if (typeOfHome == 3)
            System.out.println("\nType of Home: Condominium");
   }
}

This is used to request one of the numbers 1, 2, or 3 from the user. Any number below 1 or above 3 is not accepted. Here is an example of running the program:

What Type of House Would you Like to Purchase?
1 - Single Family
2 - Town House
3 - Condominium
Your Choice? 8
What Type of House Would you Like to Purchase?
1 - Single Family
2 - Town House
3 - Condominium
Your Choice? 6
What Type of House Would you Like to Purchase?
1 - Single Family
2 - Town House
3 - Condominium
Your Choice? 3

Type of Home: Condominium

If the user enters an invalid value, the question is simply being asked again. It would be professional to let the user know why the request came back even though what appears as a normal number was entered. To solve this and other types of problems, you can write one conditional statement inside of another. This is referred to as nesting. To create a conditional statement inside of another, simply proceed as we have done so far to create them. Here is an example:

import java.util.Scanner;

public class Exercise {
    public static int Main(String[] args) {
        int typeOfHome  = 0;

        do {
            System.out.println("What Type of House Would you Like to Purchase?");
            System.out.println("1 - Single Family");
            System.out.println("2 - Townhouse");
            System.out.println("3 - Condominium");
            System.out.print("Your Choice? ");
            typeOfHome  = scnr.nextInt();

            if ((typeOfHome  < 1) || (typeOfHome  > 3))
                System.out.println("Invalid Choice: Please try again");
        } while ((typeOfHome  < 1) || (typeOfHome  > 3));

        if (typeOfHome  == 1)
            System.out.println("Type of Home: Single Family");
        else if (typeOfHome  == 2)
            System.out.println("Type of Home: Townhouse");
        else if (typeOfHome  == 3)
            System.out.println("Type of Home: Condominium");
    }
}

Here is another example of running the program:

What Type of House Would you Like to Purchase?
1 - Single Family
2 - Town House
3 - Condominium
Your Choice? 0
Invalid Choice: Please try again
What Type of House Would you Like to Purchase?
1 - Single Family
2 - Town House
3 - Condominium
Your Choice? 6
Invalid Choice: Please try againe
What Type of House Would you Like to Purchase?
1 - Single Family
2 - Town House
3 - Condominium
Your Choice? 2

Type of Home: Town House

Practical LearningPractical Learning: Nesting a Conditional Statement

  1. To use conditional nesting, change the file as follows:
    package bcr2;
    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;
            
    
            for(int employeeCounter = 0; employeeCounter < 4; employeeCounter++) {
                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.printf("Employee #:    %d\n", employeeNumber);
                System.out.printf("Employee Name: %s\n", employeeName);
                System.out.printf("Hourly Salary: %.2f\n", hourlySalary);
                System.out.printf("Weekly Time:   %.2f\n", weeklyTime);
                System.out.printf("Regular Pay:   %.2f\n", regularPay);
                System.out.printf("Overtime Pay:  %.2f\n", overtimePay);
                System.out.printf("Total Pay:     %.2f\n", netPay);
                System.out.println("==============================");
            }
        }
    }
  2. To execute the exercise, press F6
  3. Enter the values as follows:
     
    Employee Number Hourly Salary Weekly Time
    92746 14.25 36
    54080 20.60 36.5
    82500 22.35 42.50
    86285 35.70 40
    Enter Employee Number (00000): 92746
    Enter Hourly Salary: 14.25
    Enter Weekly Time: 36
    ==============================
    =//= BETHESDA CAR RENTAL =//=
    ==-=-= Employee Payroll =-=-==
    ------------------------------
    Employee #:    92746
    Employee Name: Raymond Kouma
    
    Hourly Salary: 14.25
    Weekly Time:   36.00
    Regular Pay:   513.00
    Overtime Pay:  0.00
    Total Pay:     513.00
    ==============================
    Enter Employee Number (00000): 54080
    Enter Hourly Salary: 20.60
    Enter Weekly Time: 36.5
    ==============================
    =//= BETHESDA CAR RENTAL =//=
    ==-=-= Employee Payroll =-=-==
    ------------------------------
    Employee #:    54080
    Employee Name: Henry Larson
    Hourly Salary: 20.60
    Weekly Time:   36.50
    Regular Pay:   751.90
    Overtime Pay:  0.00
    Total Pay:     751.90
    ==============================
    Enter Employee Number (00000): 82500
    Enter Hourly Salary: 22.35
    Enter Weekly Time: 42.50
    ==============================
    =//= BETHESDA CAR RENTAL =//=
    ==-=-= Employee Payroll =-=-==
    ------------------------------
    Employee #:    82500
    Employee Name: Helene Mukoko
    Hourly Salary: 22.35
    Weekly Time:   42.50
    Regular Pay:   894.00
    Overtime Pay:  55.88
    Total Pay:     949.88
    ==============================
    Enter Employee Number (00000): 86285
    Enter Hourly Salary: 35.70
    Enter Weekly Time: 40.00
    ==============================
    =//= BETHESDA CAR RENTAL =//=
    ==-=-= Employee Payroll =-=-==
    ------------------------------
    Employee #:    86285
    Employee Name: Gertrude Monay
    Hourly Salary: 35.70
    Weekly Time:   40.00
    Regular Pay:   1428.00
    Overtime Pay:  0.00
    Total Pay:     1428.00
    ==============================

Breaking the Flow of a Conditional Statement

The break statement is used to stop a loop for any reason or condition when necessary. The formula of the break statement is:

break;

Although made of only one word, the break statement is a complete statement; therefore, it can (and should always) stay on its own line (this makes the program easy to read).

The break statement applies to the most previous conditional statement to it; provided that previous statement is applicable. The break statement can be used in a while condition, in a do…while or a for loops to stop an ongoing action. Here is an example that is used to count the levels of a house from 1 to 12 but it is asked to stop at 3:

public class Exercise {
    static void main(String[] args) {        
	for (int stories = 1; stories <= 12; stories++) {
            System.out.println("Story " + stories);

            if (stories == 3)
                break;
        }
   }
}

This would produce: 

Story 1
Story 2
Story 3

Continuing a Conditional Statement

The continue statement uses the following formula:

continue;

When processing a loop, if the statement finds a false value, you can use the continue statement inside of a while, a do…while or a for conditional statements to ignore the subsequent statement or to jump from a false Boolean value to the subsequent valid value, unlike the break statement that would exit the loop. Like the break statement, the continue keyword applies to the most previous conditional statement and should stay on its own line. Here is an example when a program is supposed to count the levels of a house from 1 to 6:

public class Exercise {
    static void main(String[] args) {        
	for (int stories = 1; stories <= 6; stories++) {
            if (stories == 3)
                continue;

            System.out.println("Story " + stories);
        }
   }
}

This would produce:

Story 1
Story 2
Story 4
Story 5
Story 6

Notice that, when the compiler gets to 3, it ignores it.

Going to a Designated Label

The break keyword allows a program execution to jump to another section of the function in which it is being used. In order to use the goto statement, insert a name on a particular section of your function so you can refer to that name. The name, also called a label, is made of one word and follows the rules we have learned about names (the name can be anything), then followed by a colon.

Conditional Return

Some functions are meant to return a value that is conditional of their processing. The fact that a function indicates the type of value it would return may not be clear at the time the function is closed but a function defined other than void must always return a value. You can write a conditional statement, such as if, inside of a function and return a value from that condition. Here is an example:

import java.util.Scanner;
 
enum HouseType {
    UNKNOWN,
    SINGLEFAMILY,
    TOWNHOUSE,
    CONDOMINIUM
}       

public class Exercise {
    static void main(String[] args) {      
	HouseType propType = specifyHouseType();

        switch(propType) {
            case SINGLEFAMILY:
                System.out.println("\nType of Home: Single Family");
                break;
            case TOWNHOUSE:
                System.out.println("\nType of Home: Townhouse");
                break;
            case CONDOMINIUM:
                System.out.println("\nType of Home: Condominium");
                break;
            case UNKNOWN:
                System.out.println("\nType of Home. Unknown");
                break;
        }
   }

   static HouseType specifyHouseType() {
        int type = 0;
	Scanner scnr = new Scanner(System.in); 

        System.out.println("What Type of House Would you Like to Purchase?");
        System.out.println("1 - Single Family");
        System.out.println("2 - Townhouse");
        System.out.println("3 - Condominium");
        System.out.print("Your Choice? ");
        type = scnr.nextInt();

        if (type == 1)
            return HouseType.SINGLEFAMILY;
        else if (type == 2)
            return HouseType.TOWNHOUSE;
        else if (type == 3)
            return HouseType.CONDOMINIUM;
    }
}

This specifyHouseType() method indicates when one of three values is returned. In reality, this method could get a value other than the three that are considered. If the user enters such a value, the current version of the method would not know what to do. For this reason, the program will not compile. To solve this problem, you must provide a statement that would include any value other than those considered. You can do this by writing a final return that has its own value. Here is an example:

import java.util.Scanner;
 
enum HouseType {
    UNKNOWN,
    SINGLEFAMILY,
    TOWNHOUSE,
    CONDOMINIUM
}       

public class Exercise {
    static void main(String[] args) {      
	HouseType propType = specifyHouseType();

        switch(propType) {
            case SINGLEFAMILY:
                System.out.println("\nType of Home: Single Family");
                break;
            case TOWNHOUSE:
                System.out.println("\nType of Home: Townhouse");
                break;
            case CONDOMINIUM:
                System.out.println("\nType of Home: Condominium");
                break;
            case UNKNOWN:
                System.out.println("\nType of Home. Unknown");
                break;
        }
   }

   static HouseType specifyHouseType() {
        int type = 0;
	Scanner scnr = new Scanner(System.in); 

        System.out.println("What Type of House Would you Like to Purchase?");
        System.out.println("1 - Single Family");
        System.out.println("2 - Townhouse");
        System.out.println("3 - Condominium");
        System.out.print("Your Choice? ");
        type = scnr.nextInt();

        if (type == 1)
            return HouseType.SINGLEFAMILY;
        else if (type == 2)
            return HouseType.TOWNHOUSE;
        else if (type == 3)
            return HouseType.CONDOMINIUM;
        else
            return HouseType.UNKNOWN;
    }
}

Recursion

 

Introduction

Imagine that you want to count the positive odd numbers from a certain maximum to a certain minimum. For example, to count the odd numbers from 1 to 9, you would use:

9, 7, 5, 3, and 1

Notice that, to perform this operation, you consider the highest. Then you subtract 2 to get the previous. Again, you subtract 2 from the number to get the previous. What you are simply doing is to subtract a constant to what you already have and you invent very little. In computer programming, you can solve this type of problem by first writing a function, and then have the function call itself. This is the basis for recursion.

Creating a Recursive Methods

 A type of formula to create a recursive method is:

ReturnValue Function(Arguments, if any){
    Optional Action . . .
    Function();
    Optionan Action . . .
}

A recursive method starts with a return value. If it would not return a value, you can define it with void. After its name, the method can take one or more arguments. Most of the time, a recursive method takes at least one argument that it would then modify. In the body of the method, you can take the necessary actions. There are no particular steps to follow when implementing a recursive method but there are two main rules to observe:

  • In its body, the method must call itself
  • Before or after calling itself, the method must check a condition that would allow it to stop, otherwise, it might run continuously

For our example of counting decrementing odd numbers, you could start by creating a method that takes an integer as argument. To exercise some control on the lowest possible values, we will consider only positive numbers. In the body of the method, we will display the current value of the argument, subtract 2, and recall the method itself. Here is our function:

public class Exercise {
    static void showOddNumber(int a)    {
        if (a >= 1)        {
            System.out.println(a);
            a -= 2;
            showOddNumber(a);
        }
    }

    static void main(String[] args) {      
	final int Number = 9;

        System.out.println("Odd Numbers");
        showOddNumber(Number);
   }
}

Notice that the method calls itself in its body. This would produce:

Odd Numbers
9
7
5
3
1

Using Recursive Methods

Recursive methods provide a valuable mechanism for building lists or series, which are value that are either increment or decrement but follow a pattern. Imagine that, instead of simply displaying odd numbers as we did above, you want to add them incrementally. If you have 1, it would also produce 1. If you have 5, you would like to add 1 to 3, then the result to 5, and so on. This can be illustrated as follows:

                1 = 1
            1 + 3 = 4
        1 + 3 + 5 = 9
    1 + 3 + 5 + 7 = 16
1 + 3 + 5 + 7 + 9 = 25

To perform this operation, you would consider 1. If the number is less than or equal to 1, the method should return 1. Otherwise, add 2 to 1, then add 2 to the new result. Continue this until you get to the value of the argument. The method can be implemented as follows:

public class Exercise {
    static int getAdditionalOdd(int a) {
        if (a <= 1)
            return 1;
        return a + getAdditionalOdd(a - 2);
    }

    static void showOddNumbers(int a)    {
        if (a >= 1) {
            System.out.println(a);
            a -= 2;
           showOddNumbers(a);
        }
    }
    
    static void main(String[] args) {
        final int number = 9;

        System.out.println("Odd Numbers");
        showOddNumbers(number);

        System.out.println("Sum of Odds: " + getAdditionalOdd(number));
   }
}

This would produce:

Odd Numbers
9
7
5
3
1
Sum of Odds: 25

 

 

Logical Disjunction

 

Previous Copyright © 2008-2012, FunctionX Next