Home

Conditional Statements

 

if a Condition is True

 

Introduction

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 LearningPractical Learning: Introducing Conditional Statements

  1. Start NetBeans and create a Java Application named bcr1
  2. 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);
        }
    
    }
  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, 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

if

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 LearningPractical Learning: Using an if Statement

  1. 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");
            }
        }
    }
  2. To execute the exercise, press F6
  3. 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
  4. Execute the application again
  5. 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
  6. Execute the application again
  7. 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
  8. Close the message box and the DOS window then return to your programming environment

if…else

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 LearningPractical Learning: Using if...Else

  1. 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("==============================");
        }
    }
  2. Execute the application
  3. Enter the Employee name as 82500, the hourly salary as 22.35, and the weekly time as 42.50
  4. 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 LearningPractical Learning: Using an if…else if…else Statement 

  1. 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("======================");
        }
    }
  2. To execute the exercise, press F6
  3. 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
    ==============================
  4. Execute the application again
  5. Enter the Employee number as 82500, the hourly salary as 22.35, and the weekly hours as 42.50, then press Enter
  6. Execute the application again
  7. Enter the Employee number as 86285, the hourly salary as 35.70, and the weekly hours as 40.00, then press Enter
 

 

 

 

 

 

 

 

 

 

 

 

 

 

Case Switches

 

Introduction

When defining an expression whose result would lead to a specific program execution, the switch statement considers that result and executes a statement based on the possible outcome of that expression, this possible outcome is called a case. The different outcomes are listed in the body of the switch statement and each case has its own execution, if necessary. The body of a switch statement is delimited from an opening to a closing curly brackets: “{“ to “}”. The syntax of the switch statement is:

switch(Expression){
    case Choice1:
         Statement1;
	break;
    case Choice2:
         Statement2;
	break;
    case Choice-n:
         Statement-n;
	break;
}

The expression to examine in a case statement is an integer. Since a member of an enumerator (enum) and the character (char) data types are just other forms of integers, they can be used too. Here is an example of using the switch statement:

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();

        switch (Choice) {
            case 1:
                Type = HouseType.SINGLEFAMILY;
                break;

            case 2:
                Type = HouseType.TOWNHOUSE;
                break;

            case 3:
                Type = HouseType.CONDOMINIUM;
                break;
        }

        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);
    }
}
Author Note In Java as well as in C++ (but not in C#), you can omit the break keyword in a case. This creates the "fall through" effect as follows: after code executes in a case, if nothing "stops" it, the execution continues to the next case. This has caused problems and confusing execution in the past in some C++ programs.

When establishing the possible outcomes that the switch statement should consider, at times there will be possibilities other than those listed and you will be likely to consider them. This special case is handled by the default keyword. The default case would be considered if none of the listed cases matches the supplied answer. The syntax of the switch statement that considers the default case would be:

switch(Expression){
    case Choice1:
         Statement1;
	break;
    case Choice2:
         Statement2;
	break;
    case Choice-n:
         Statement-n;
	break;
    default:
         Other-Possibility;
	break;
}

Therefore another version of the program above would be

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();

        switch (Choice)        {
            case 1:
                Type = HouseType.SINGLEFAMILY;
                break;

            case 2:
                Type = HouseType.TOWNHOUSE;
                break;

            case 3:
                Type = HouseType.CONDOMINIUM;
                break;

            default:
                Type = HouseType.UNKNOWN;
                break;
        }

        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? 8
Does the house have an indoor garage (1=Yes/0=No)? 2

Desired House Type: UNKNOWN
Has indoor garage?  No

Besides a value of an int type, you can also use another variant of integers on a switch statement. For example, you can use letters to validate the cases. 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();

        switch (Choice)        {
            case 1:
                Type = HouseType.SINGLEFAMILY;
                break;

            case 2:
                Type = HouseType.TOWNHOUSE;
                break;

            case 3:
                Type = HouseType.CONDOMINIUM;
                break;

            default:
                Type = HouseType.UNKNOWN;
                break;
        }

        System.out.print("Does the house have an indoor garage (1=Yes/0=No)? ");
        int Answer = scnr.nextInt();
        
        switch (Answer)
        {
            case 'y':
                Garage = "Yes";
                break;

            case 'Y':
                Garage = "Yes";
                break;

            case 'n':
                Garage = "No";
                break;

            case 'N':
                Garage = "No";
                break;

            default:
                Garage = "Not Specified";
                break;
        }

        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 (y/n)? y

Desired House Type: Condominium
Has indoor garage?  Yes

Combining Cases

Each of the cases we have used so far examined only one possibility before executing the corresponding statement. You can combine cases to execute the same statement. To do this, type a case, its value, and the semi-colon. Type another case using the same formula. When the cases are ready, you can then execute the desired statement.

Using Enumerations

One of the most fundamental uses of enumerations is to process them in a switch statement. To do this, you pass the value of an enumeration to a switch. The values of the enumerations are then processed in the case statements.

 
 

Previous Copyright © 2008-2012, FunctionX Next