Foundations of Switching a Case

Introduction

By now, we know that a conditional statement is a section of code that performs one or more comparisons on values and allows you to make a decision. In previous lessons, we performed those comparisons using logical operators and special keywords to make decisions. There are even more options to assist you in making decisions

Practical LearningPractical Learning: Switching a String

  1. Start Microsoft Visual Studio (if Microsoft Visual Studio was already opened, on its main menu, click File -> New -> Project...) and create a new Console App that supports .NET 7.0 (Standard Term Support) named TaxPreparation09
  2. Change the document as follows:
    using static System.Console;
    
    WriteLine("==========================================");
    WriteLine(" - Amazing DeltaX - State Income Tax -");
    WriteLine("==========================================");
    
    string stateName = "";
    double taxRate   = 0.00;
    
    WriteLine("Enter the information for tax preparation");
    WriteLine("States");
    WriteLine(" AK - Alaska");
    WriteLine(" AR - Arkansas");
    WriteLine(" CO - Colorado");
    WriteLine(" FL - Florida");
    WriteLine(" GA - Georgia");
    WriteLine(" IL - Illinois");
    WriteLine(" IN - Indiana");
    WriteLine(" KY - Kentucky");
    WriteLine(" MA - Massachusetts");
    WriteLine(" MI - Michigan");
    WriteLine(" MO - Missouri");
    WriteLine(" MS - Mississippi");
    WriteLine(" NV - Nevada");
    WriteLine(" NH - New Hampshire");
    WriteLine(" NC - North Carolina");
    WriteLine(" PA - Pennsylvania");
    WriteLine(" SD - South Dakota");
    WriteLine(" TN - Tennessee");
    WriteLine(" TX - Texas");
    WriteLine(" UT - Utah");
    WriteLine(" WA - Washington");
    WriteLine(" WY - Wyoming");
    Write("Enter State Abbreviation: ");
    string abbr = ReadLine();
    WriteLine("--------------------------------------------");
            
    Write("Gross Salary:             ");
    double grossSalary = double.Parse(ReadLine());
    
    double taxAmount = grossSalary * taxRate / 100.00;
    double netPay    = grossSalary - taxAmount;
    
    WriteLine("============================================");
    WriteLine(" - Amazing DeltaX - State Income Tax -");
    WriteLine("--------------------------------------------");
    WriteLine($"Gross Salary: {grossSalary:f}");
    WriteLine($"State:        {stateName}");
    WriteLine($"Tax Rate:     {taxRate:f}%");
    WriteLine("--------------------------------------------");
    WriteLine($"Tax Amount:   {taxAmount:f}");
    WriteLine($"Net Pay:      {netPay:f}");
    WriteLine("============================================");
  3. To execute the project, on the main menu, click Debug -> Start Without Debugging
  4. For the State Abbreviation, type FL and press Enter
  5. For the Gross Salary, type 1558.85 and press Enter:
    ==========================================
     - Amazing DeltaX - State Income Tax -
    ==========================================
    Enter the information for tax preparation
    States
     AK - Alaska
     AR - Arkansas
     CO - Colorado
     FL - Florida
     GA - Georgia
     IL - Illinois
     IN - Indiana
     KY - Kentucky
     MA - Massachusetts
     MI - Michigan
     MO - Missouri
     MS - Mississippi
     NV - Nevada
     NH - New Hampshire
     NC - North Carolina
     PA - Pennsylvania
     SD - South Dakota
     TN - Tennessee
     TX - Texas
     UT - Utah
     WA - Washington
     WY - Wyoming
    Enter State Abbreviation: FL
    --------------------------------------------
    Gross Salary: 1558.85
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
    Gross Salary: 1558.85
    State:
    Tax Rate:     0.00%
    --------------------------------------------
    Tax Amount:   0.00
    Net Pay:      1558.85
    ============================================
    Press any key to close this window . . .
  6. Press any key to close the window and return to your programming environment
  7. To execute the project again, on the main menu, click Debug -> Start Without Debugging
  8. For the State Abbreviation, type KY and press Enter
  9. For the Gross Salary, type 1558.85 and press Enter:
    ==========================================
     - Amazing DeltaX - State Income Tax -
    ==========================================
    Enter the information for tax preparation
    States
     AK - Alaska
     AR - Arkansas
     CO - Colorado
     FL - Florida
     GA - Georgia
     IL - Illinois
     IN - Indiana
     KY - Kentucky
     MA - Massachusetts
     MI - Michigan
     MO - Missouri
     MS - Mississippi
     NV - Nevada
     NH - New Hampshire
     NC - North Carolina
     PA - Pennsylvania
     SD - South Dakota
     TN - Tennessee
     TX - Texas
     UT - Utah
     WA - Washington
     WY - Wyoming
    Enter State Abbreviation: KY
    --------------------------------------------
    Gross Salary:             1558.85
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
    Gross Salary: 1558.85
    State:
    Tax Rate:     0.00%
    --------------------------------------------
    Tax Amount:   0.00
    Net Pay:      1558.85
    ============================================
    Press any key to close this window . . .
  10. Press any key to close the window and return to your programming environment

A Case for a Conditional Selection

In a typical application, you have many comparisons to make. Some comparisons involve many variables but some comparisons are performed on only one variable and values. This means that you may have a situation where you want to compare one variable to many values. This time, you create a list of comparisons, then select which outcome applies to the conclusion you need to establish.

To perform a series of comparisons of one variable with one or more values, you use a keyword named switch. Like most comparison operators, including if that we saw in previous lessons, the switch keyword requires parentheses, as in switch(). In the parentheses, you must type the existing name of the variable on which you want to perform comparisons. In the previous lessons, we saw that the if operator doesn't require curly brackets if its code includes only one line of code but requires curly brackets if its body includes more than one line of code. The switch() conditional statement always uses more than one line of code. Therefore, it requires a body delimited by curly brackets:

switch(variable-name)
{
}

Once again, the section from the opening curly bracket ({) to the closing curly bracket (}) is the body of the switch() conditional statement. In that body, you must create one or more sections that would perform the necessary selections. Each section is created with a keyword named case. The case keyword creates its own section that includes the actual processing that must occur. As a result, this keyword must have its own delimiting body. Exceptionally (this is the only C# topic that functions like that), the body of a case section starts with a colon (:) and ends with a keyword named break, which is a statement and therefore must end with a semicolon. Therefore, the formula to create a switch statement is:

switch(expression)
{
    case choice1:
        statement1;
	break;
    case choice2:
        statement2;
	break;
    case choice-n:
        statement-n;
	break;
}

As mentioned above, you start with the switch() statement that is followed by a body delimited by curly brackets. In the parentheses of switch(), you can put the name of a variable. That variable must already exist and must hold a valid value. As we will see in later sections. The value in the parentheses of switch() can also be an expression that can be evaluated to a valid value. The body of the switch statement contains one or more sections that each starts with the case keyword. Each case section uses a body from a colon to a break; line. In that body, you will write code to process the outcome of that case or selection.

The switch statement accepts different types of expressions or values.

Switching an Integer

Probably the most regularly used type of value in a switch expression is a natural number. The object or expression passed to the switch can come from any source as long as it represents a constant integer.

In most cases, a switch statement behaves like an if conditional statement except that an if conditional statement may use fewer lines of code. Consider the following code that uses an if conditional statement:

using static System.Console;

int number = 248;
string conclusion = "That number is not right.";

if(number == 248)
    conclusion = "That number is correct.";
        
WriteLine(conclusion);
WriteLine("========================================");

This would produce:

That number is correct.
========================================
Press any key to close this window . . .

The same code can be written with a switch statement as follows:

using static System.Console;

int number = 248;
string conclusion = "That number is not right.";

switch (number)
{
    case 248:
        conclusion = "That number is correct.";
        break;
}

WriteLine(conclusion);
WriteLine("========================================");

We know that an if conditional statement can use one or more else options. Here is an example:

using static System.Console;

double incomeTax = 0.00;

WriteLine("Payroll Evaluation");
WriteLine("============================================");
WriteLine("Enter the information to evaluate taxes");
WriteLine("Frequency by which the payroll is processed:");
WriteLine("1 - Weekly");
WriteLine("2 - Biweekly");
WriteLine("3 - Semimonthly");
WriteLine("4 - Monthly");
Write("Enter Payroll Frequency: ");
int frequency = int.Parse(ReadLine());
WriteLine("--------------------------------------------");

Write("Gross Salary:            ");
double grossSalary = double.Parse(ReadLine());

if(frequency == 1)
    incomeTax = 271.08 + (grossSalary * 24 / 100);
else if(frequency == 2)
        incomeTax = 541.82 + (grossSalary * 24 / 100);
else if(frequency == 3)
    incomeTax = 587.12 + (grossSalary * 24 / 100);
else if(frequency == 4)
    incomeTax = 1174.12 + (grossSalary * 24 / 100);

WriteLine("============================================");
WriteLine("Payroll Evaluation");
WriteLine("--------------------------------------------");
WriteLine("Gross Salary: {0,10:n}", grossSalary);
WriteLine("Income Tax:   {0,10:n}", incomeTax);
WriteLine("============================================");

In the same way, a switch statement can use many cases. Here is an example:

using static System.Console;

double incomeTax = 0.00;

WriteLine("Payroll Evaluation");
WriteLine("============================================");
WriteLine("Enter the information to evaluate taxes");
WriteLine("Frequency by which the payroll is processed:");
WriteLine("1 - Weekly");
WriteLine("2 - Biweekly");
WriteLine("3 - Semimonthly");
WriteLine("4 - Monthly");
Write("Enter Payroll Frequency: ");
int frequency = int.Parse(ReadLine());
WriteLine("--------------------------------------------");

Write("Gross Salary:            ");
double grossSalary = double.Parse(ReadLine());

switch (frequency)
{
    case 1:
        incomeTax = 271.08 + (grossSalary * 24 / 100);
        break;
    case 2:
        incomeTax = 541.82 + (grossSalary * 24 / 100);
        break;
    case 3:
        incomeTax = 587.12 + (grossSalary * 24 / 100);
        break;
    case 4:
        incomeTax = 1174.12 + (grossSalary * 24 / 100);
        break;
}

WriteLine("============================================");
WriteLine("Payroll Evaluation");
WriteLine("--------------------------------------------");
WriteLine("Gross Salary: {0,10:n}", grossSalary);
WriteLine("Income Tax:   {0,10:n}", incomeTax);
WriteLine("============================================");

Switching a String

Besides a natural number, a switch statement can perform its case comparisons on a string value, such as a variable that holds a string value or an expression that produces a string. This means that each case must consider a possible value that the variable or expression may hold.

Practical LearningPractical Learning: Switching by Some Strings

  1. Change the document as follows:
    using static System.Console;
    
    WriteLine("==========================================");
    WriteLine(" - Amazing DeltaX - State Income Tax -");
    WriteLine("==========================================");
    
    string stateName = "";
    double taxRate   = 0.00;
    
    WriteLine("Enter the information for tax preparation");
    WriteLine("States");
    WriteLine(" AK - Alaska");
    WriteLine(" AR - Arkansas");
    WriteLine(" CO - Colorado");
    WriteLine(" FL - Florida");
    WriteLine(" GA - Georgia");
    WriteLine(" IL - Illinois");
    WriteLine(" IN - Indiana");
    WriteLine(" KY - Kentucky");
    WriteLine(" MA - Massachusetts");
    WriteLine(" MI - Michigan");
    WriteLine(" MO - Missouri");
    WriteLine(" MS - Mississippi");
    WriteLine(" NV - Nevada");
    WriteLine(" NH - New Hampshire");
    WriteLine(" NC - North Carolina");
    WriteLine(" PA - Pennsylvania");
    WriteLine(" SD - South Dakota");
    WriteLine(" TN - Tennessee");
    WriteLine(" TX - Texas");
    WriteLine(" UT - Utah");
    WriteLine(" WA - Washington");
    WriteLine(" WY - Wyoming");
    Write("Enter State Abbreviation: ");
    string abbr = ReadLine();
    WriteLine("--------------------------------------------");
            
    Write("Gross Salary: ");
    double grossSalary = double.Parse(ReadLine());
    
    switch (abbr)
    {
        case "CO":
            taxRate   = 4.63;
            stateName = "Colorado";
            break;
        case "FL":
            taxRate   = 0.00;
            stateName = "Florida";
            break;
        case "IL":
            taxRate   = 4.95;
            stateName = "Illinois";
            break;
        case "IN":
            taxRate   = 3.23;
            stateName = "Indiana";
            break;
        case "KY":
            taxRate   = 5.00;
            stateName = "Kentucky";
            break;
        case "MA":
            taxRate   = 5.00;
            stateName = "Massachusetts";
            break;
        case "MI":
            taxRate   = 4.25;
            stateName = "Michigan";
            break;
        case "NC":
            taxRate   = 5.25;
            stateName = "North Carolina";
            break;
        case "NH":
            taxRate   = 5.00;
            stateName = "New Hampshire";
            break;
        case "NV":
            taxRate   = 0.00;
            stateName = "Nevada";
            break;
        case "PA":
            taxRate   = 3.07;
            stateName = "Pennsylvania";
            break;
        case "TN":
            taxRate = 1.00;
            stateName = "Tennessee";
            break;
        case "TX":
            taxRate   = 0.00;
            stateName = "Texas";
            break;
        case "UT":
            taxRate   = 4.95;
            stateName = "Utah";
            break;
        case "WA":
            taxRate   = 0.00;
            stateName = "Washington";
            break;
        case "WY":
            taxRate   = 0.00;
            stateName = "Wyoming";
            break;
    }
    
    double taxAmount = grossSalary * taxRate / 100.00;
    double netPay    = grossSalary - taxAmount;
    
    WriteLine("============================================");
    WriteLine(" - Amazing DeltaX - State Income Tax -");
    WriteLine("--------------------------------------------");
    WriteLine($"Gross Salary: {grossSalary:f}");
    WriteLine($"State:        {stateName}");
    WriteLine($"Tax Rate:     {taxRate:f}%");
    WriteLine("--------------------------------------------");
    WriteLine($"Tax Amount:   {taxAmount:f}");
    WriteLine($"Net Pay:      {netPay:f}");
    WriteLine("============================================");
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging
  3. For the State Abbreviation, type CO and press Enter
  4. For the Gross Salary, type 1558.85 and press Enter:
    ==========================================
     - Amazing DeltaX - State Income Tax -
    ==========================================
    Enter the information for tax preparation
    States
     AK - Alaska
     AR - Arkansas
     CO - Colorado
     FL - Florida
     GA - Georgia
     IL - Illinois
     IN - Indiana
     KY - Kentucky
     MA - Massachusetts
     MI - Michigan
     MO - Missouri
     MS - Mississippi
     NV - Nevada
     NH - New Hampshire
     NC - North Carolina
     PA - Pennsylvania
     SD - South Dakota
     TN - Tennessee
     TX - Texas
     UT - Utah
     WA - Washington
     WY - Wyoming
    Enter State Abbreviation: CO
    --------------------------------------------
    Gross Salary:             1558.85
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
    Gross Salary: 1558.85
    State:        Colorado
    Tax Rate:     4.63%
    --------------------------------------------
    Tax Amount:   72.17
    Net Pay:      1486.68
    ============================================
    Press any key to close this window . . .
  5. Press any key to close the window and return to your programming environment
  6. To execute the project again, on the main menu, click Debug -> Start Without Debugging
  7. For the State Abbreviation, type KY and press Enter
  8. For the Gross Salary, type 1558.85 and press Enter:
    ==========================================
     - Amazing DeltaX - State Income Tax -
    ==========================================
    Enter the information for tax preparation
    States
     AK - Alaska
     AR - Arkansas
     CO - Colorado
     FL - Florida
     GA - Georgia
     IL - Illinois
     IN - Indiana
     KY - Kentucky
     MA - Massachusetts
     MI - Michigan
     MO - Missouri
     MS - Mississippi
     NV - Nevada
     NH - New Hampshire
     NC - North Carolina
     PA - Pennsylvania
     SD - South Dakota
     TN - Tennessee
     TX - Texas
     UT - Utah
     WA - Washington
     WY - Wyoming
    Enter State Abbreviation: KY
    --------------------------------------------
    Gross Salary:             1558.85
    ============================================
     - Amazing DeltaX - State Income Tax -
    --------------------------------------------
    Gross Salary: 1558.85
    State:        Kentucky
    Tax Rate:     5.00%
    --------------------------------------------
    Tax Amount:   77.94
    Net Pay:      1480.91
    ============================================
    Press any key to close this window . . .
  9. Press any key to close the window and return to your programming environment
  10. Create a new Console App that supports the .NET 6.0 (Long-Term Support) and named SimpleInterest1

Switching an Enumeration

The switch operation supports values based on an enumeration. When creating the statement, you can pass an expression that holds the value of an enumeration. In the body of the switch clause, each case can represent one of the members of the enumeration.

Practical LearningPractical Learning: Switching an Enumeration

  1. Change the Program.cs document as follows:
    using static System.Console;
    
    double frequency = 0.00;
    double interestRate = 0.00;
    int periods = 42;
    CompoundFrequency compounding = CompoundFrequency.Monthly;
    
    WriteLine("Simple Interest");
    WriteLine("--------------------------------------------------------");
    WriteLine("Provide the values that will be used to evaluate a loan.");
    Write("Principal: ");
    double principal = double.Parse(ReadLine());
    WriteLine("--------------------------------------------------------");
    WriteLine("Compound Frequencies");
    WriteLine("1. Weekly");
    WriteLine("2. Monthly");
    WriteLine("3. Quaterly");
    WriteLine("4. Semiannually");
    WriteLine("5. Annually");
    Write("Type your choice: ");
    string choice = ReadLine();
    
    if (choice == "1")
        compounding = CompoundFrequency.Weekly;
    else if (choice == "2")
        compounding = CompoundFrequency.Monthly;
    else if (choice == "3")
        compounding = CompoundFrequency.Quaterly;
    else if (choice == "4")
        compounding = CompoundFrequency.Semiannually;
    else if (choice == "5")
        compounding = CompoundFrequency.Annually;
    else
        compounding = CompoundFrequency.Daily;
    
    switch (compounding)
    {
        case CompoundFrequency.Daily:
            interestRate = 8.95;
            frequency = 365.00;
            break;
            
        case CompoundFrequency.Weekly:
            frequency = 52.00;
            interestRate = 11.95;
            break;
            
        case CompoundFrequency.Monthly:
            frequency = 12.00;
            interestRate = 14.75;
            break;
            
        case CompoundFrequency.Quaterly:
            frequency = 4.00;
            interestRate = 18.85;
            break;
            
        case CompoundFrequency.Semiannually:
            frequency = 2.00;
            interestRate = 22.55;
            break;
            
        case CompoundFrequency.Annually:
            frequency = 1.00;
            interestRate = 26.25;
            break;
    }
    
    double iRate = interestRate / 100;
    double per = periods / frequency;
    double interestAmount = principal * iRate * per;
    
    WriteLine("=========================================================");
    WriteLine("Simple Interest");
    WriteLine("--------------------------------------------------------");
    WriteLine("Principal:          {0:f}", principal);
    WriteLine("Interest Rate:      {0}%", interestRate);
    WriteLine("Periods:            {0} months", periods);
    WriteLine("-------------------------------");
    WriteLine("Interest Amount:    {0:f}", interestAmount);
    WriteLine("Future Value:       {0:f}", principal + interestAmount);
    Write("=========================================================");
    
    public enum CompoundFrequency { Daily, Weekly, Monthly, Quaterly, Semiannually, Annually }
  2. To execute, press Ctrl + F5
  3. When requested, type the Principal as 7248.95 and press Enter
  4. For the compound frequency, type 2 and press Enter:
    Simple Interest
    --------------------------------------------------------
    Provide the values that will be used to evaluate a loan.
    Principal: 7248.95
    --------------------------------------------------------
    Compound Frequencies
    1. Weekly
    2. Monthly
    3. Quaterly
    4. Semiannually
    5. Annually
    Type your choice: 2
    =========================================================
    Simple Interest
    --------------------------------------------------------
    Principal:          7248.95
    Interest Rate:      14.75%
    Periods:            42 months
    -------------------------------
    Interest Amount:    3742.27
    Future Value:       10991.22
    =========================================================
    Press any key to close this window . . .
  5. Press T to close the window and return to your programming environment

Conditionally Switching

Introduction

We saw that a switch conditional statement can process natural numbers and strings. It can also process Boolean values or logical expression. To proceed, you can write a Boolean variable or an expression that produces a Boolean value in the parentheses of switch(). Then, one case can consider a true value and another case would consider a false value. Here is an example:

using static System.Console;

string conclusion;
string emplTitle     = "Manager";
bool   emplIsManager = emplTitle == "Manager";

switch (emplIsManager)
{
    case true:
        conclusion = "The employee is a manager.";
        break;
    case false:
        conclusion = "The staff member is a regular employee.";
        break;
}

WriteLine(conclusion);
WriteLine("========================================");

This would produce:

The employee is a manager.
========================================
Press any key to close this window . . .

Switching a Boolean Expression

In the previous example, in the parentheses of switch(), we included a variable that held a Boolean value. As an alternative, you can include a Boolean expression. Here is an example:

using static System.Console;

string conclusion;
string emplTitle = "Manager";

switch(emplTitle == "Manager")
{
    case true:
        conclusion = "The employee is a manager.";
        break;
    case false:
        conclusion = "The staff member is a regular employee.";
        break;
}

WriteLine(conclusion);
WriteLine("========================================");

Otherwise, all the other comparison operators we studied can also be used. Here is an example:

using static System.Console;

double timeWorked = 30.00;

// If TimeWorked >= 40
switch (timeWorked >= 40.00)
{
    case true:
        WriteLine("The employee works full-time.");
        break;
    case false:
        WriteLine("The staff member worked part-time.");
        break;
}

WriteLine("========================================");

The main idea is to know how to convert an if conditional statement that uses a logical expression such as this:

using static System.Console;

WriteLine("FUN DEPARTMENT STORE");
WriteLine("=======================================================");
WriteLine("Payroll Preparation");
WriteLine("-------------------------------------------------------");
WriteLine("Enter the following pieces of information");
WriteLine("-------------------------------------------------------");
WriteLine("Employee Information");
WriteLine("-------------------------------------------------------");
Write("First Name:    ");
string firstName = ReadLine();
Write("Last Name:     ");
string lastName = ReadLine();
Write("Hourly Salary: ");
double hSalary = double.Parse(ReadLine());
WriteLine("-------------------------------------------------------");
WriteLine("Time worked");
WriteLine("-------------------------------------------------------");

Write("Monday:        ");
double mon = double.Parse(ReadLine());

Write("Tuesday:       ");
double tue = double.Parse(ReadLine());

Write("Wednesday:     ");
double wed = double.Parse(ReadLine());

Write("Thursday:      ");
double thu = double.Parse(ReadLine());

Write("Friday:        ");
double fri = double.Parse(ReadLine());

double timeWorked = mon + tue + wed + thu + fri;

double regTime, overtime;
double regPay, overPay;

if(timeWorked <= 40.00)
{
    regTime = timeWorked;
    regPay = hSalary * timeWorked;
    overtime = 0.00;
    overPay = 0.00;
}
else
{
    regTime  = 40.00;
    regPay   = hSalary * 40.00;
    overtime = timeWorked - 40.00;
    overPay  = hSalary * 1.50 * overtime;
}

double netPay = regPay + overPay;

WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+");
WriteLine("FUN DEPARTMENT STORE");
WriteLine("=======================================================");
WriteLine("Payroll Evaluation");
WriteLine("=======================================================");
WriteLine("Employee Information");
WriteLine("-------------------------------------------------------");
WriteLine($"Full Name:     {firstName} {lastName}");
WriteLine($"Hourly Salary: {hSalary:f}");
WriteLine("=======================================================");
WriteLine("Time Worked Summary");
WriteLine("--------+---------+-----------+----------+-------------");
WriteLine(" Monday | Tuesday | Wednesday | Thursday | Friday");
WriteLine("--------+---------+-----------+----------+-------------");
WriteLine($"  {mon:f}  |   {tue:f}  |    {wed:f}   |   {thu:f}   |  {fri:f}");
WriteLine("========+=========+===========+==========+=============");
WriteLine("                                    Pay Summary");
WriteLine("-------------------------------------------------------");
WriteLine("                                   Time   Pay");
WriteLine("-------------------------------------------------------");
WriteLine($"                     Regular:    {regTime:f}   {regPay:f}");
WriteLine("-------------------------------------------------------");
WriteLine($"             overtime:    {overtime:f}   {overPay:f}");
WriteLine("=======================================================");
WriteLine($"                     Net Pay:            {netPay:f}");
WriteLine("=======================================================");

into a switch statement like this:

using static System.Console;

WriteLine("FUN DEPARTMENT STORE");
WriteLine("=======================================================");
        
	. . .

double regTime, overtime;
double regPay, overPay;

switch(timeWorked <= 40.00)
{
    case true:
        regTime  = timeWorked;
        regPay   = hSalary * timeWorked;
        overtime = 0.00;
        overPay  = 0.00;
        break;
    case false:
        regTime  = 40.00;
        regPay   = hSalary * 40.00;
        overtime = timeWorked - 40.00;
        overPay  = hSalary * 1.50 * overtime;
        break;
}

double netPay = regPay + overPay;

        . . .

WriteLine("=======================================================");
WriteLine($"                     Net Pay:            {netPay:f}");
WriteLine("=======================================================");

Conditionally Selecting a Case

If you submit a Boolean variable or a logical expression to the parentheses of a switch(), you can process only two value, true and false. As we saw with if else conditional statements, sometimes you have many possibilities you need to consider. To do this in a switch(), you can create different cases and let each consider an outcome. In this case, for each section, type case followed by the desired logical operator and the corresponding value. In the body of the case section, write the code for that comparison. If all cases use the Less Than operator, the case must be listed from the lowest to the highest values. Here are examples:

using static System.Console;

WriteLine("FUN DEPARTMENT STORE"); ;
WriteLine("=======================================================");
WriteLine("Item Preparation"); ;
WriteLine("-------------------------------------------------------");
WriteLine("Enter the following pieces of information"); ;
WriteLine("-------------------------------------------------------");

int discountRate = 75;
double discountAmount = 0.00;
double discountedPrice = 0.00;

Write("Item Name:        ");
string itemName = ReadLine();
Write("Original Price:   ");
double originalPrice = double.Parse(ReadLine());
Write("Days in Store:    ");
int daysInStore = int.Parse(ReadLine());

switch (daysInStore)
{
    case < 15:
        discountRate = 0;
        break;
    case < 35:
        discountRate = 15;
        break;
    case < 45:
        discountRate = 35;
        break;
    case < 60:
        discountRate = 50;
        break;
}

discountAmount = originalPrice * discountRate / 100;
discountedPrice = originalPrice - discountAmount;

WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+");
WriteLine("FUN DEPARTMENT STORE"); ;
WriteLine("=======================================================");
WriteLine("Store Inventory"); ;
WriteLine("-------------------------------------------------------");
WriteLine($"Item Name:        {itemName}"); ;
WriteLine($"Original Price:   {originalPrice}"); ;
WriteLine($"Days in Store:    {daysInStore}"); ;
WriteLine($"Discount Rate:    {discountRate}%"); ;
WriteLine($"Discount Amount:  {discountAmount:f}"); ;
WriteLine($"Discounted Price: {discountedPrice:f}"); ;
WriteLine("=======================================================");

If the cases are using a > operator, they must be listed from the highest to the lowest values. Here are examples:

using static System.Console;

WriteLine("Stellar Water Point");
WriteLine("======================================================");
WriteLine("To prepare an invoice, enter the following information");
WriteLine("Types of Accounts");
WriteLine("1. Residential Household");
WriteLine("2. Laudromat");
WriteLine("3. Health Clinic");
WriteLine("4. Place of Worship/Youth Center");
WriteLine("5. Government Agency");
WriteLine("6. Other Business");
Write("Enter Type of Account:         ");
string answer = ReadLine();
WriteLine("------------------------------------------------------");

Write("Counter Reading Start:         ");
double counterReadingStart = double.Parse(ReadLine());
Write("Counter Reading End:           ");
double counterReadingEnd = double.Parse(ReadLine());

double first25Therms, next15Therms, above40Therms;

double gallons = counterReadingEnd - counterReadingStart;
double HCFTotal = gallons / 748;

switch(HCFTotal)
{
    case > 40.00:
        first25Therms = 25.00 * 1.5573;
        next15Therms  = 15.00 * 1.2264;
        above40Therms = (HCFTotal - 40.00) * 0.9624;
        break;
    case > 25.00:
        first25Therms = 25.00 * 1.5573;
        next15Therms  = (HCFTotal - 25.00) * 1.2264;
        above40Therms = 0.00;
        break;
}

double waterUsageCharges = first25Therms + next15Therms + above40Therms;
double sewerCharges = waterUsageCharges * 0.252;

double environmentCharges = (answer == "1") ? (waterUsageCharges * 0.0025) : (waterUsageCharges * 0.0125);

double serviceCharges = (answer == "1") ? (waterUsageCharges * 0.0328)
                                                    : (waterUsageCharges * 0.11643);

double totalCharges = waterUsageCharges + sewerCharges + environmentCharges + serviceCharges;

double localTaxes = (answer == "1") ? (totalCharges * 0.035) : (totalCharges * 0.235);
double stateTaxes = (answer == "1") ? (totalCharges * 0.115) : (totalCharges * 0.815);

double amountDue = totalCharges + localTaxes + stateTaxes;

WriteLine("======================================================");
WriteLine("Stellar Water Point - Customer Invoice");
WriteLine("======================================================");
WriteLine("Meter Reading");
WriteLine("------------------------------------------------------");
WriteLine("Counter Reading Start:      {0,10}", counterReadingStart);
WriteLine("Counter Reading End:        {0,10}", counterReadingEnd);
WriteLine("Total Gallons Consumed:     {0,10}", gallons);
WriteLine("======================================================");
WriteLine("Therms Evaluation");
WriteLine("------------------------------------------------------");
WriteLine("HCF Total:                  {0,10:n}", HCFTotal);
WriteLine("First 35 Therms (* 1.5573): {0,10:n}", first25Therms);
WriteLine("First 20 Therms (* 1.2264): {0,10:n}", next15Therms);
WriteLine("Above 40 Therms (* 0.9624): {0,10:n}", above40Therms);
WriteLine("------------------------------------------------------");
WriteLine("Water Usage Charges:        {0,10:n}", waterUsageCharges);
WriteLine("Sewer Charges:              {0,10:n}", sewerCharges);
WriteLine("======================================================");
WriteLine("Bill Values");
WriteLine("------------------------------------------------------");
WriteLine("Environment Charges:        {0,10:n}", environmentCharges);
WriteLine("Service Charges:            {0,10:n}", serviceCharges);
WriteLine("Total Charges:              {0,10:n}", totalCharges);
WriteLine("Local Taxes:                {0,10:n}", localTaxes);
WriteLine("State Taxes:                {0,10:n}", stateTaxes);
WriteLine("------------------------------------------------------");
WriteLine("Amount Due:                 {0,10:n}", amountDue);
WriteLine("======================================================");

Default Selection

Introduction

When you create a switch statement, you ask it to consider each of the values that can fit the expression in the parentheses of switch(). Normally, you cannot match all the possible or available values. To consider a case that would apply to all possible values that don't fit the expression in the parentheses of switch(), you use a keyword named default. If you don't want to consider any particular value, you can create a switch statement that uses only a default case. The formula you would follow is:

switch(expression)
{
    default:
	statement(s);
	break;
}

Start with the default keyword. Like any case selection, the default section must have a body. The body of the default section starts with a colon after the default keyword and ends with a break; line. In the body, you can write any appropriate code you want. A lone default statement applies to every value, regardless of any condition you set. Here is an example:

using static System.Console;

int number = 125;

switch(number < 100)
{
    default:
        WriteLine("Number: {0}", number);
        break;
}

This would produce:

Number: 125
Press any key to close this window . . .

Here is another version of the same program:

using static System.Console;

int number = 125;

switch(number > 100)
{
    default:
	WriteLine("Number: {0}", number);
	break;
}

That version produces the same result as the other.

Switching to the default Outcome

We saw that, when all outcomes of an if statement have been considered but none of them fits, you can issue an else statement that would process all conditions that didn't fit any of the if and/or else if situations. Also, the else statement must be the last in an if conditional statement. To address the same type of issue, you can add a default case to a switch statement. The formula to follow would be:

switch(expression)
{
    case choice1:
        statement1;
    	break;
    case choice2:
        statement2;
    	break;
    case choice-n:
        statement-n;
    	break;
    default:
        default-statement;
    	break;
}

The rules of the default case are:

Here is an example:

using static System.Console;

WriteLine("==========================================");
WriteLine(" - Amazing DeltaX - State Income Tax -");
WriteLine("==========================================");

double taxRate   = 0.00;

WriteLine("Enter the information for tax preparation");
WriteLine("States");
WriteLine(" AK - Alaska");
WriteLine(" AR - Arkansas");
WriteLine(" CO - Colorado");
WriteLine(" FL - Florida");
WriteLine(" GA - Georgia");
WriteLine(" IL - Illinois");
WriteLine(" IN - Indiana");
WriteLine(" KY - Kentucky");
WriteLine(" MA - Massachusetts");
WriteLine(" MI - Michigan");
WriteLine(" MO - Missouri");
WriteLine(" MS - Mississippi");
WriteLine(" NV - Nevada");
WriteLine(" NH - New Hampshire");
WriteLine(" NC - North Carolina");
WriteLine(" PA - Pennsylvania");
WriteLine(" SD - South Dakota");
WriteLine(" TN - Tennessee");
WriteLine(" TX - Texas");
WriteLine(" UT - Utah");
WriteLine(" WA - Washington");
WriteLine(" WY - Wyoming");
Write("Enter State Abbreviation: ");
string abbr = ReadLine();
WriteLine("--------------------------------------------");
        
Write("Gross Salary:             ");
double grossSalary = double.Parse(ReadLine());

switch (abbr)
{
    default: // "Florida", "Nevada", "Texas", "Washington", "Wyoming"
        taxRate   = 0.00;
        break;
    case "CO":
        taxRate   = 4.63;
        break;
    case "KY":
        taxRate   = 5.00;
        break;
    case "IL":
        taxRate   = 4.95;
        break;
    case "IN":
        taxRate   = 3.23;
        break;
    case "MA":
        taxRate   = 5.00;
        break;
    case "MI":
        taxRate   = 4.25;
        break;
    case "NC":
        taxRate   = 5.25;
        break;
    case "NH":
        taxRate   = 5.00;
        break;
    case "PA":
        taxRate   = 3.07;
        break;
    case "TN":
        taxRate = 1.00;
        break;
    case "UT":
        taxRate   = 4.95;
        break;
}

double taxAmount = grossSalary * taxRate / 100.00;
double netPay    = grossSalary - taxAmount;

WriteLine("============================================");
WriteLine(" - Amazing DeltaX - State Income Tax -");
WriteLine("--------------------------------------------");
WriteLine($"Gross Salary: {grossSalary:f}");
WriteLine($"Tax Rate:     {taxRate:f}%");
WriteLine("--------------------------------------------");
WriteLine($"Tax Amount:   {taxAmount:f}");
WriteLine($"Net Pay:      {netPay:f}");
WriteLine("============================================");

Here is an example of running the program:

==========================================
 - Amazing DeltaX - State Income Tax -
==========================================
Enter the information for tax preparation
States
 AK - Alaska
 AR - Arkansas
 CO - Colorado
 FL - Florida
 GA - Georgia
 IL - Illinois
 IN - Indiana
 KY - Kentucky
 MA - Massachusetts
 MI - Michigan
 MO - Missouri
 MS - Mississippi
 NV - Nevada
 NH - New Hampshire
 NC - North Carolina
 PA - Pennsylvania
 SD - South Dakota
 TN - Tennessee
 TX - Texas
 UT - Utah
 WA - Washington
 WY - Wyoming
Enter State Abbreviation: WA
--------------------------------------------
Gross Salary:             2285.88
============================================
 - Amazing DeltaX - State Income Tax -
--------------------------------------------
Gross Salary: 2285.88
Tax Rate:     0.00%
--------------------------------------------
Tax Amount:   0.00
Net Pay:      2285.88
============================================
Press any key to close this window . . .

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2001-2024, FunctionX Saturday 29 April 2023, 11:26 PM Next