Options on Conditional Switches
Options on Conditional Switches
The Default and Case Combinations
When considering the possible outcomes of a switch statement, 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 formula of the switch statement that considers the default case is:
switch(expression) { case choice1: statement1; break; case choice2: statement2; break; case choice-n: statement-n; break; default: default-statement; break; }
In some languages, the default section doesn't require a break keyword because it is the last. In C#, every case and the default section must have its own exit mechanism, which is taken care of by a break keyword.
Practical Learning: Switching to a Default Outcome
<!DOCTYPE html> <html> <head> <title>State Income Tax - Flat-Rate States</title> <style> .container { margin: auto; width: 320px; } </style> </head> <body> <div class="container"> @{ string state = ""; double salary = 0.00; string strTaxes = "0.00"; string strNetPay = "0.00"; string residence = ""; if (IsPost) { double taxes = 0.00; state = Request["cbxStates"]; salary = Convert.ToDouble(Request["txtGrossSalary"]); switch (state) { case "Colorado": taxes = salary * 4.63 / 100.00; residence = "Colorado (4.63%)"; break; case "Illinois": taxes = salary * 3.75 / 100.00; residence = "Illinois (3.75%)"; break; case "Indiana": taxes = salary * 3.3 / 100.00; residence = "Indiana (3.3%)"; break; case "Michigan": taxes = salary * 4.25 / 100.00; residence = "Michigan (4.25%)"; break; case "North Carolina": taxes = salary * 5.75 / 100.00; residence = "North Carolina (5.75%)"; break; case "Pennsylvania": taxes = salary * 3.07 / 100.00; residence = "Pennsylvania (3.07%)"; break; case "Utah": taxes = salary * 5 / 100.00; residence = "Utah (5%)"; break; default: taxes = 0.00; residence = ""; break; } strTaxes = taxes.ToString("F"); strNetPay = (salary - taxes).ToString("F"); } } <h3 style="text-align: center">State Income Tax</h3> <h4 style="text-align: center">Flat-Rate States</h4> <form name="frmIncomeTax" method="post"> <table> <tr> <td style="width: 150px">Gross Salary:</td> <td><input type="text" name="txtGrossSalary" value="@salary" /></td> </tr> <tr> <td>State:</td> <td> <select name="cbxStates"> <option value="Nothing"></option> <option value="Colorado">Colorado</option> <option value="Illinois">Illinois</option> <option value="Indiana">Indiana</option> <option value="Michigan">Michigan</option> <option value="North Carolina">North Carolina</option> <option value="Pennsylvania">Pennsylvania</option> <option value="Utah">Utah</option> </select> </td> </tr> <tr> <td> </td> <td style="text-align: center"><input type="submit" name="btnCalculate" value="Calculate" /></td> </tr> <tr> <td>Employee Residence:</td> <td><input type="text" name="txtEmployeeResidence" value="@residence" /></td> </tr> <tr> <td>State Income Tax:</td> <td><input type="text" name="txtIncomeTax" value="@strTaxes" /></td> </tr> <tr> <td>Net Pay:</td> <td><input type="text" name="txtNetPay" value="@strNetPay" /></td> </tr> </table> </form> </div> </body> </html>
Case Combinations
Although each case must consider only one value, you may have a situation where different case values must deal with the same outcome. In this case, you can combine those cases. To do this, type case followed by its value and a colon. On the next line, create another case with its value and colon. You can continue that for each value that fits that group. Then write the common code of those cases and end the section with the required break keyword and its semicolon.
Practical Learning: Combining Cases in a Switch
<!DOCTYPE html> <html> <head> <title>State Income Tax - Flat-Rate States</title> <style> .container { margin: auto; width: 320px; } </style> </head> <body> <div class="container"> @{ string state = ""; double salary = 0.00; string strTaxes = "0.00"; string strNetPay = "0.00"; string residence = ""; if (IsPost) { double taxes = 0.00; state = Request["cbxStates"]; salary = Convert.ToDouble(Request["txtGrossSalary"]); switch (state) { case "Colorado": taxes = salary * 4.63 / 100.00; residence = "Colorado (4.63%)"; break; case "Alaska": case "Florida": // Two of the 9 states that don't collect an income tax taxes = 0.00; residence = "No Income Tax"; break; case "Illinois": taxes = salary * 3.75 / 100.00; residence = "Illinois (3.75%)"; break; case "Indiana": taxes = salary * 3.3 / 100.00; residence = "Indiana (3.3%)"; break; case "Nevada": case "New Hampshire": case "Tennessee": case "Texas": // Four other states that don't collect an income tax taxes = 0.00; residence = "Income Tax Not Collected"; break; case "Michigan": taxes = salary * 4.25 / 100.00; residence = "Michigan (4.25%)"; break; case "North Carolina": taxes = salary * 5.75 / 100.00; residence = "North Carolina (5.75%)"; break; case "South Dakota": case "Washington": case "Wyoming": // Three other states that don't collect an income tax taxes = 0.00; residence = "Income Tax Not Paid"; break; case "Pennsylvania": taxes = salary * 3.07 / 100.00; residence = "Pennsylvania (3.07%)"; break; case "Utah": taxes = salary * 5 / 100.00; residence = "Utah (5%)"; break; default: taxes = 0.00; residence = ""; break; } strTaxes = taxes.ToString("F"); strNetPay = (salary - taxes).ToString("F"); } } <h3 style="text-align: center">State Income Tax</h3> <h4 style="text-align: center">Flat-Rate States</h4> <form name="frmIncomeTax" method="post"> <table> <tr> <td style="width: 150px">Gross Salary:</td> <td><input type="text" name="txtGrossSalary" value="@salary" /></td> </tr> <tr> <td>State:</td> <td> <select name="cbxStates"> <option value="Nothing"></option> <option value="Wyoming">Wyoming</option> <option value="Texas">Texas</option> <option value="Colorado">Colorado</option> <option value="Florida">Florida</option> <option value="Illinois">Illinois</option> <option value="Washington">Washington</option> <option value="Indiana">Indiana</option> <option value="Alaska">Alaska</option> <option value="Michigan">Michigan</option> <option value="Nevada">Nevada</option> <option value="New Hampshire">New Hampshire</option> <option value="South Dakota">South Dakota</option> <option value="North Carolina">North Carolina</option> <option value="Tennessee">Tennessee</option> <option value="Pennsylvania">Pennsylvania</option> <option value="Utah">Utah</option> </select> </td> </tr> <tr> <td> </td> <td style="text-align: center"><input type="submit" name="btnCalculate" value="Calculate" /></td> </tr> <tr> <td>Employee Residence:</td> <td><input type="text" name="txtEmployeeResidence" value="@residence" /></td> </tr> <tr> <td>State Income Tax:</td> <td><input type="text" name="txtIncomeTax" value="@strTaxes" /></td> </tr> <tr> <td>Net Pay:</td> <td><input type="text" name="txtNetPay" value="@strNetPay" /></td> </tr> </table> </form> </div> </body> </html>
Nesting a Conditional Statement in a Case
Each case of a switch statement has its own body in which you can create a conditional statement. This is referred to as nesting.
Practical Learning: Nesting a Conditional Statement in a Case
<!DOCTYPE html> <html> <head> <title>Payroll Preparation - Federal Withholding Taxes</title> <style> .container { margin: auto; width: 320px; } </style> </head> <body> @{ int exemptions = 0; decimal salary = 0.00m; string filingStatus = ""; string strAllowances = "0.00"; string strFederalIncomeTax = "0.00"; string strTaxableGrossWages = "0.00"; if (IsPost) { decimal withheldAmount = 0; decimal allowanceRate = 77.90m; salary = Request["txtGrossSalary"].AsDecimal(); filingStatus = Request["cbxFilingStatus"]; exemptions = Request["txtExemptions"].AsInt(); decimal withheldingAllowances = allowanceRate * exemptions; decimal taxableGrossWages = salary - withheldingAllowances; switch (filingStatus) { case "Single": if (taxableGrossWages <= 44) { withheldAmount = 0; } else if ((taxableGrossWages > 44m) && (taxableGrossWages <= 224m)) { withheldAmount = (taxableGrossWages - 44m) * 10 / 100; } else if ((taxableGrossWages > 224m) && (taxableGrossWages <= 774m)) { withheldAmount = 18.00m + ((taxableGrossWages - 224) * 15 / 100); } else if ((taxableGrossWages > 774m) && (taxableGrossWages <= 1812)) { withheldAmount = 100.50m + ((taxableGrossWages - 774) * 25 / 100); } else if ((taxableGrossWages > 1812m) && (taxableGrossWages <= 3730)) { withheldAmount = 360.00m + ((taxableGrossWages - 1812) * 28 / 100); } else if ((taxableGrossWages > 3730m) && (taxableGrossWages <= 8058)) { withheldAmount = 897.04m + ((taxableGrossWages - 3730) * 33 / 100); } else if ((taxableGrossWages > 8058m) && (taxableGrossWages <= 8090)) { withheldAmount = 2325.28m + ((taxableGrossWages - 8058) * 35 / 100); } else // if (taxableGrossWages > 8090m) { withheldAmount = 2336.48m + ((taxableGrossWages - 8090m) * 39.60m / 100m); } break; case "Married": if (taxableGrossWages <= 166) { withheldAmount = 0; } else if ((taxableGrossWages > 166) && (taxableGrossWages <= 525)) { withheldAmount = (taxableGrossWages - 166) * 10 / 100; } else if ((taxableGrossWages > 525) && (taxableGrossWages <= 1626)) { withheldAmount = 35.90m + ((taxableGrossWages - 525) * 15 / 100); } else if ((taxableGrossWages > 1626) && (taxableGrossWages <= 3111)) { withheldAmount = 201.05m + ((taxableGrossWages - 1626) * 25 / 100); } else if ((taxableGrossWages > 3111) && (taxableGrossWages <= 4654)) { withheldAmount = 572.30m + ((taxableGrossWages - 3111) * 28 / 100); } else if ((taxableGrossWages > 4654) && (taxableGrossWages <= 8180)) { withheldAmount = 1004.34m + ((taxableGrossWages - 4654) * 33 / 100); } else if ((taxableGrossWages > 8160) && (taxableGrossWages <= 9218)) { withheldAmount = 2167.92m + ((taxableGrossWages - 8180) * 35 / 100); } else // if (taxableGrossWages > 9218) { withheldAmount = 2531.22m + ((taxableGrossWages - 9218) * 39.60m / 100); } break; } strAllowances = withheldingAllowances.ToString("F"); strTaxableGrossWages = taxableGrossWages.ToString("F"); strFederalIncomeTax = withheldAmount.ToString("F"); } } <div class="container"> <h3 style="text-align: center">Payroll Preparation</h3> <h4 style="text-align: center">Federal Withholding Taxes</h4> <form name="frmIncomeTax" method="post"> <table> <tr> <td style="width: 150px">Gross Salary:</td> <td><input type="text" name="txtGrossSalary" value="@salary" /></td> </tr> <tr> <td>Filing as:</td> <td> <select name="cbxFilingStatus"> <option value="Nothing"></option> <option value="Single">Single</option> <option value="Married">Married</option> </select> </td> </tr> <tr> <td style="width: 150px">Exemptions:</td> <td><input type="text" name="txtExemptions" value="@exemptions" /></td> </tr> <tr> <td> </td> <td style="text-align: center"><input type="submit" name="btnCalculate" value="Calculate" onclick="ShowMessageBox" /></td> </tr> <tr> <td>Filing Status:</td> <td><input type="text" name="txtFilingStatus" value="@filingStatus" /></td> </tr> <tr> <td>Allowances:</td> <td><input type="text" name="txtAllowances" value="@strAllowances" /></td> </tr> <tr> <td>Taxable Gross Wages:</td> <td><input type="text" name="txtTaxableGrossWages" value="@strTaxableGrossWages" /></td> </tr> <tr> <td>Federal Income Tax:</td> <td><input type="text" name="txtFederalIncomeTax" value="@strFederalIncomeTax" /></td> </tr> </table> </form> </div> </body> </html>
Pattern Matching
When Switching a Value
So far, we have seen that, when creating a switch statement, create a case clause in a switch statement. The case keyword can be followed by either a constant value or an expression. Here are examples:
switch (number) { case 1: selected = h; break; case 2: selected = he; break; case 3: selected = li; break; }
Pattern matching consists of applying a condition to a case. In a case of a switch statement, you can include a conditional statement that compares its value to another to actually validate the case. This is done using the when keyword. The formula to follow is:
case value-or-expression when logical-expression: statement(s)
As mentioned already, the case is followed by a constant or an expression, The new keyword is when. It is followed by a logical expression.
When Switching a Variable
After a case keyword, you can declare a variable of the same type as the value used in the switch() parentheses. Follow the variable with the when keyword followed by a logical expression that equates the variable to the case value. The variable is "visible" only with its case. Therefore, you can use the same variable in every case.
When Switching to a Null Case
When working on a switch statement that deals with an object such as a string, you may have a situation where none of the values can apply. In this situation, one of the cases would be null. In this case, you can include a case whose value is null. Here is an example:
<!DOCTYPE html> <html> <head> <title>Real Estate</title> </head> <body> @{ string result = ""; string answer = ""; if (IsPost) { if(Request["txtAnswer"] == "") { answer = null; } else { answer = Request["txtAnswer"]; } switch (answer) { case "y": result = "The answer is Yes"; break; case "n": result = "Your answer: No"; break; case null: result = "NULL"; break; } } } <h3>Real Estate</h3> <h4>House Description</h4> <form name="frmExercise" method="post"> <p>Are you sure (Type y or n)? <input name="txtAnswer" type="text" value="@answer" /> <input type="submit" name="btnAnswer" value="Answer" /></p> <p>@result</p> </form> </body> </html>
Options on Pattern Matching
When Patterning a Conditional Statement
The when expression is used to apply a conditional statement. It can consist of an expression that uses any of the Boolean operators we are familiar with. It may look as follows:
switch(number) { case value-or-expression when number > 8: statement(s); break; }
The following example is for a company that makes and sells office chairs. Each chair has a weight and a price. A customer can order a certain number of chairs, which results in a calculated sub-total (the number of chairs multiplied by the price of a chair). When acustomer places an order, a discount is based on the sub-total amount of the order. The shipping and handling of a customer order is based on the total weight of the chairs ordered. |
Practical Learning: Introducing Conditions in Pattern Matching
<!DOCTYPE html> <html> <head> <title>Office Suppliers Store - Office Chairs</title> <style> .container { margin: auto; width: 520px; } .centeredText{ text-align: center; } .columnWidth { width: 110px } .txtBox { width: 60px; } </style> </head> <body> @{ int quantity = 0; decimal weight = 0; decimal unitPrice = 0; string strSubTotal = ""; string strTotalWeight = ""; string strDiscountRate = ""; string strInvoiceAmount = ""; string strDiscountAmount = ""; string strShippingAndHandling = ""; if (IsPost) { decimal shipping = 0; decimal discountRate = 0; quantity = Request["txtQuantity"].AsInt(); unitPrice = Request["txtUnitPrice"].AsDecimal(); weight = Request["txtWeight"].AsDecimal(); decimal subTotal = quantity * unitPrice; decimal totalWeight = quantity * weight; switch (subTotal) { case decimal discount when subTotal >= 800: discountRate = 20; // % break; case decimal discount when subTotal >= 600: discountRate = 15; // % break; case decimal discount when subTotal >= 300: discountRate = 10; // % break; default: // double discount when subTotal < 300) discountRate = 0; // % break; } switch (totalWeight) { case decimal sh when totalWeight >= 200: shipping = 42.50M; break; case decimal sh when totalWeight >= 150: shipping = 36.25M; break; case decimal sh when totalWeight >= 100: shipping = 24.48M; break; case decimal sh when totalWeight >= 50: shipping = 18.65M; break; default: // double sh when totalWeight < 50) shipping = 12.25M; break; } decimal discountAmount = subTotal * discountRate / 100; decimal invoiceDue = subTotal - discountAmount; decimal InvoiceAmount = invoiceDue + shipping; strSubTotal = subTotal.ToString("F"); strDiscountRate = discountRate.ToString("F"); strDiscountAmount = discountAmount.ToString("F"); strTotalWeight = totalWeight.ToString("F"); strShippingAndHandling = shipping.ToString("F"); strInvoiceAmount = InvoiceAmount.ToString("F"); } } <form name="frmFurniture" method="post" class="container"> <h2 class="centeredText">Office Suppliers Store</h2> <h3 class="centeredText">Office Chairs</h3> <table> <tr> <td class="columnWidth">Quantity:</td> <td class="columnWidth"><input type="text" class="txtBox" name="txtQuantity" value="@quantity" /></td> <td class="columnWidth"> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td>Unit Price:</td> <td><input type="text" class="txtBox" name="txtUnitPrice" value="@unitPrice" /></td> <td>Weight:</td> <td><input type="text" class="txtBox" name="txtWeight" value="@weight" /></td> <td>Pounds</td> <td><input type="submit" name="btnCalculate" value="Calculate" /></td> </tr> </table> <hr /> <table> <tr> <td class="columnWidth">Sub-Total:</td> <td class="columnWidth"><input type="text" name="txtSubTotal" class="txtBox" value="@strSubTotal" /></td> <td style="width: 40px"> </td> <td style="width: 150px"> </td> <td style="width: 120px"> </td> </tr> <tr> <td>Discount Rate:</td> <td><input type="text" name="txtDiscountRate" style="width: 40px;" value="@strDiscountRate" />%</td> <td> </td> <td>Discount Amount:</td> <td><input type="text" name="txtDiscountAmount" class="txtBox" value="@strDiscountAmount" /></td> </tr> </table> <hr /> <table> <tr> <td class="columnWidth">Total Weight:</td> <td class="columnWidth"><input type="text" name="txtTotalWeight" style="width: 40px;" value="@strTotalWeight" /> Pounds</td> <td style="width: 40px"> </td> <td>Shipping && Handling:</td> <td><input type="text" name="txtShippingAndHandling" class="txtBox" value="@strShippingAndHandling" /></td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td>Invoice Amount:</td> <td><input type="text" name="txtInvoiceAmount" class="txtBox" value="@strInvoiceAmount" /></td> </tr> </table> </form> <div> </div> </body> </html>
Quantity: 3 Unit Price: 127.50 Weight: 62.38
Quantity: 3 Unit Price: 95.75 Weight: 58.74
Patterning Different Types of Values
When using a switch statement, the values involved must be of the same type or compatible. Otherwise, you can find a way to convert them.
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2001-2019, FunctionX | Next |
|