Options on Conditional Switches
Options on Conditional Switches
Combining Conditional Switches
Nesting a Conditional Statement in a Case
Each case of a switch statement has its own body. In that body, you write any code necessary for the outcome of that case. To process that outcome, you can create one or more conditional statements. This is the same as nesting one or more conditional statements, as we saw when studying conditional conjunctions and disjunctions.
Practical Learning: Switching a String
using static System.Console; WriteLine("=========================================="); WriteLine(" - Amazing DeltaX - State Income Tax -"); WriteLine("=========================================="); string stateName = ""; double taxRate = 0.00; double amountAdded = 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; amountAdded = 0.00; stateName = "Colorado"; break; case "FL": taxRate = 0.00; amountAdded = 0.00; stateName = "Florida"; break; case "KY": taxRate = 5.00; amountAdded = 0.00; stateName = "Kentucky"; break; case "IL": taxRate = 4.95; amountAdded = 0.00; stateName = "Illinois"; break; case "IN": taxRate = 3.23; stateName = "Indiana"; break; case "MA": taxRate = 5.00; amountAdded = 0.00; stateName = "Massachusetts"; break; case "MI": taxRate = 4.25; amountAdded = 0.00; stateName = "Michigan"; break; case "NC": taxRate = 5.25; amountAdded = 0.00; stateName = "North Carolina"; break; case "NH": taxRate = 5.00; amountAdded = 0.00; stateName = "New Hampshire"; break; case "NV": taxRate = 0.00; amountAdded = 0.00; stateName = "Nevada"; break; case "PA": taxRate = 3.07; amountAdded = 0.00; stateName = "Pennsylvania"; break; case "TN": taxRate = 1.00; amountAdded = 0.00; stateName = "Tennessee"; break; case "TX": taxRate = 0.00; amountAdded = 0.00; stateName = "Texas"; break; case "UT": taxRate = 4.95; amountAdded = 0.00; stateName = "Utah"; break; case "WA": taxRate = 0.00; amountAdded = 0.00; stateName = "Washington"; break; case "WY": taxRate = 0.00; amountAdded = 0.00; stateName = "Wyoming"; break; case "MO": stateName = "Missouri"; if ((grossSalary >= 0.00) && (grossSalary <= 106)) { amountAdded = 0; taxRate = 0.00; } else if((grossSalary > 106) && (grossSalary <= 1_073)) { amountAdded = 0; taxRate = 1.50; } else if((grossSalary > 1_073) && (grossSalary <= 2_146)) { amountAdded = 16; taxRate = 2.00; } else if((grossSalary > 2_146) && (grossSalary <= 3_219)) { amountAdded = 37; taxRate = 2.50; } else if((grossSalary > 3_219) && (grossSalary <= 4_292)) { amountAdded = 64; taxRate = 3.00; } else if((grossSalary > 4_292) && (grossSalary <= 5_365)) { amountAdded = 96; taxRate = 3.50; } else if((grossSalary > 5_365) && (grossSalary <= 6_438)) { amountAdded = 134; taxRate = 4.00; } else if((grossSalary > 6_438) && (grossSalary <= 7_511)) { amountAdded = 177; taxRate = 4.50; } else if((grossSalary > 7_511) && (grossSalary <= 8_584)) { amountAdded = 225; taxRate = 5.00; } else // if(grossSalary > 8_584) { amountAdded = 279; taxRate = 5.40; } break; } double taxAmount = amountAdded + (grossSalary * taxRate / 100.00); double netPay = grossSalary - taxAmount; WriteLine("============================================"); WriteLine(" - Amazing DeltaX - State Income Tax -"); WriteLine("============================================"); WriteLine($" {stateName}"); WriteLine("--------------------------------------------"); WriteLine($"Gross Salary: {grossSalary:f}"); WriteLine($"Tax Rate: {taxRate:f}%"); WriteLine("--------------------------------------------"); WriteLine($"Tax Amount: {taxAmount:f}"); WriteLine($"Net Pay: {netPay:f}"); WriteLine("============================================");
========================================== - 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: MO -------------------------------------------- Gross Salary: 2688.75 ============================================ - Amazing DeltaX - State Income Tax - ============================================ Missouri -------------------------------------------- Gross Salary: 2688.75 Tax Rate: 2.50% -------------------------------------------- Tax Amount: 104.22 Net Pay: 2584.53 ============================================ Press any key to close this window . . .
using static System.Console; /* The Traffic Tickets System is a small (console/terminal-based) application * that allows a fictitious government (in the United States) or to assist * a fictitious police department to manage traffic tickets, tickets based on * the types of roads, the types of signs posted on roads, the speed limits, * the traffic lights, etc. * This is an application for entertainment purposes only. Don't take any * aspect of this application seriously. */ /* The Violation variable is used to identify the type of violation * or infraction that was committed by a driver. */ int violation; /* We will use the TypeOfIssue variable to address some concerns or * situation(s) related to the person who is operating a vehicle. */ int typeOfIssue; // Because every road has a speed limit, which is usually clearly posted // on the side of a road, our application wants to know the speed limit... */ int drivingSpeed; // ... and the speed at which the vehicle was proceeding. int postedSpeedLimit; /* The following two variables are used to set the amount of a ticket * (remember that this application is just for entertainment purposes). */ double baseTicket = 0.00; double additionalFee = 0.00; // These variables will be used to display the summary of the ticket. string strPeriod; string strRoadType = ""; string strTypeOfIssue = ""; string strTypeOfViolation = ""; WriteLine("Traffic Tickets System"); WriteLine("=========================================================="); /* Starting here, a police officer, a government clerk, or a designated * user is used an application on a computer. We want the person * to make selections on the application. * We want to know the period during which the infraction was committed. */ WriteLine("Periods"); WriteLine("1 - Monday-Friday - Night (7PM - 6AM)"); WriteLine("2 - Monday-Friday - Morning Rush Hour (6AM - 9AM)"); WriteLine("3 - Monday-Friday - Regular Time (9AM - 3PM)"); WriteLine("4 - Monday-Friday - Afternoon Rush Hour (3PM - 7PM)"); WriteLine("5 - Weekend (Saturday-Sunday) and Holidays"); WriteLine("----------------------------------------------------------"); Write("Period of the infraction (1-5): "); int period = int.Parse(ReadLine()); switch (period) { case 1: strPeriod = "Monday-Friday - Night (7PM - 6AM)"; break; case 2: strPeriod = "Monday-Friday - Morning Rush Hour (6AM - 9AM)"; break; default: // case 3: strPeriod = "Monday-Friday - Regular Time (9AM - 3PM)"; break; case 4: strPeriod = "Monday-Friday - Afternoon Rush Hour (3PM - 7PM)"; break; case 5: strPeriod = "Weekend (Saturday-Sunday) and Holidays"; break; } WriteLine("=========================================================="); // We want to know the type or category of road where the violation was committed. WriteLine("Type of Road"); // Interstate issues include slow driving, fast driving, aggressive driving, etc. WriteLine("1 - Interstate (Ex. I95)"); /* Federal/State Highway include the characteristics of Interstate roads. * Although many federal and state highways appear like interstate roads, * some of those highways have traffic lights (green light, orange light, * red light, flashing orange lights, flashing red lights). */ WriteLine("2 - Federal/State Highway (Ex. US50)"); // State roads include the same issues as Federal/State Highway. Some State roads may have Stop signs. WriteLine("3 - State Road (Ex. TN22, MD410)"); // County/Local roads include the same issues as State roads. Additionally, they have Stop signs. WriteLine("4 - County/Local Road (Ex. Randolph Rd, Eusebio Ave, Abena Blvd) or Local - Unknown (Ex. Sterling Str, Garvey Court)"); WriteLine("----------------------------------------------------------"); Write("Type of road (1-4): "); int roadType = int.Parse(ReadLine()); switch (roadType) { case 1: strRoadType = "Interstate"; break; case 2: strRoadType = "Federal/State Highway"; break; case 3: strRoadType = "State Road"; break; default: // case 4: strRoadType = "County/Local Road, Others"; break; } WriteLine("=========================================================="); // Let the user specify the speed limit on the road Write("Posted Speed Limit: "); postedSpeedLimit = int.Parse(ReadLine()); // The application wants to know at what speed the vehicle was operated Write("Driving Speed: "); drivingSpeed = int.Parse(ReadLine()); WriteLine("=========================================================="); /* Everything considered, or no matter what, there are issues related either to the driver * who is operating the vehicle, or issues related to the vehicles. We will mention some of those issues here. */ WriteLine("Types of issues"); WriteLine("0 - No particular issues"); WriteLine("1 - Health issues"); WriteLine("2 - Driving while sleeping"); WriteLine("3 - Driving while using an electronic device"); WriteLine("4 - Driving under the influence (of alcohol, drugs, intoxicating products, etc)"); Write("Type of issue (0-4): "); typeOfIssue = int.Parse(ReadLine()); if (typeOfIssue == 1) { /* The driver was found with a health related issue. * Try to assist the driver who is probably having an issue. * If the driver is having a health issue: * 1. Ask to park the car on the road shoulder if possible * 2. Get an "In case of emergency" number from the driver and call a family member, friend, etc * 3. Call an ambulance to take the driver to an Emergency Room * 4. Don't issue a ticket */ baseTicket = 0.00; strTypeOfIssue = "Health issues"; } else if (typeOfIssue == 2) { /* If the driver is sleeping while driving: * 1. If the driver is having a health issue, proceed as in the previous section. * If not, take the driver into custody * 2. Impound the vehicle * 3. Issue a ticket: $100 */ baseTicket = 150.00; strTypeOfIssue = "Driving while sleeping"; } else if (typeOfIssue == 3) { /* If the driver is using an electronic device (cellphone, etc) while driving: * 1. Stop the driver * 2. Issue a ticket: $150 (and let the driver go) */ baseTicket = 100.00; strTypeOfIssue = "Driving while using an electronic device"; } else if (typeOfIssue == 4) { /* If the driver is operating the vehicle while intoxicated: * 1. Stop the vehicle. * Find out whether it is a legitimate medical/health issue. * If that's the case, do as in the first case. If not: * 2. Impound the vehicle * 3. (Normally, or in reality, the driver must appear in court * where a traffic judge will make all the decisions; but for * the sake of our simple application, ...) * Issue a ticket: $350 */ baseTicket = 350.00; strTypeOfIssue = "Driving under the influence (alcohol, drugs, intoxicating products, or else)"; } else // if (typeOfIssue == 0) { baseTicket = 0.00; strTypeOfIssue = "No particular issues relatted to the traffic violation"; } WriteLine("=========================================================="); /* For our entertainment-based application, the amount of ticket * will depend on the type of road where the violation took place. */ if (roadType == 1) // Interstate { WriteLine("Type of Traffic Violation"); WriteLine("1 - Slow Driving"); WriteLine("2 - Fast Driving"); WriteLine("3 - Aggressive Driving"); WriteLine("4 - Unknown - Other"); WriteLine("----------------------------------------------------------"); Write("Type of violaction (1-4): "); violation = int.Parse(ReadLine()); switch (violation) { case 1: additionalFee = 0.00; strTypeOfViolation = "Slow Driving"; break; case 2: additionalFee = 100.00; strTypeOfViolation = "Fast Driving"; break; case 3: additionalFee = 125.00; strTypeOfViolation = "Aggressive Driving"; break; default: // case 4: additionalFee = 50.00; strTypeOfViolation = "Unknown - Other"; break; } } else if (roadType == 2) { WriteLine("Type of Traffic Violation"); WriteLine("1 - Slow Driving"); WriteLine("2 - Fast Driving"); WriteLine("3 - Aggressive Driving"); WriteLine("4 - Driving Through Steady Red Light"); WriteLine("5 - Driving Through Flashing Red Light"); WriteLine("6 - Red Light Right Turn Without Stopping"); WriteLine("7 - Unknown - Other"); WriteLine("----------------------------------------------------------"); Write("Type of violaction (1-7): "); violation = int.Parse(ReadLine()); switch (violation) { case 1: additionalFee = 0.00; strTypeOfViolation = "Slow Driving"; break; case 2: additionalFee = 65.00; strTypeOfViolation = "Fast Driving"; break; case 3: additionalFee = 75.00; strTypeOfViolation = "Aggressive Driving"; break; case 4: additionalFee = 105.00; strTypeOfViolation = "Driving Through Steady Red Light"; break; case 5: additionalFee = 35.00; strTypeOfViolation = "Driving Through Flashing Red Light"; break; case 6: additionalFee = 25.00; strTypeOfViolation = "Red Light Right Turn Without Stopping"; break; default: // case 8 or other: additionalFee = 5.00; strTypeOfViolation = "Unknown - Other"; break; } } else { WriteLine("Type of Traffic Violation"); WriteLine("1 - Slow Driving"); WriteLine("2 - Fast Driving"); WriteLine("3 - Aggressive Driving"); WriteLine("4 - Driving Through Steady Red Light"); WriteLine("5 - Driving Through Flashing Red Light"); WriteLine("6 - Red Light Right Turn Without Stopping"); WriteLine("7 - Driving Through Stop Sign Without Stopping"); WriteLine("8 - Unknown - Other"); WriteLine("----------------------------------------------------------"); Write("Type of violaction (1-8): "); violation = int.Parse(ReadLine()); switch (violation) { case 1: additionalFee = 0.00; strTypeOfViolation = "Slow Driving"; break; case 2: additionalFee = 35.00; strTypeOfViolation = "Fast Driving"; break; case 3: additionalFee = 55.00; strTypeOfViolation = "Aggressive Driving"; break; case 4: additionalFee = 65.00; strTypeOfViolation = "Driving Through Steady Red Light"; break; case 5: additionalFee = 55.00; strTypeOfViolation = "Driving Through Flashing Red Light"; break; case 6: additionalFee = 35.00; strTypeOfViolation = "Red Light Right Turn Without Stopping"; break; case 7: additionalFee = 15.00; strTypeOfViolation = "Driving Through Stop Sign Without Stopping"; break; default: // case 8 or other: additionalFee = 5.00; strTypeOfViolation = "Unknown - Other"; break; } } WriteLine("=========================================================="); WriteLine("Traffic Ticket Summary"); WriteLine("----------------------------------------------------------"); WriteLine("Period of the day: {0}", strPeriod); WriteLine("Road Type: {0}", strRoadType); WriteLine("Posted Speed Limit: {0}", postedSpeedLimit); WriteLine("Driving Speed: {0}", drivingSpeed); WriteLine("Type of Issue: {0}", strTypeOfIssue); WriteLine(" Base Ticket: {0}", baseTicket); WriteLine("Violation Type: {0}", strTypeOfViolation); WriteLine(" Addition Fee: {0}", additionalFee); WriteLine("----------------------------------------------------------"); WriteLine("Ticket Amount: {0}", baseTicket + additionalFee); WriteLine("==========================================================");
Periods: 1 Type of Road: 1 Posted Speed Limit: 60 Driving Speed: 120 Type of Issue: 3 --------------------------------- Traffic Tickets System ========================================================== Periods 1 - Monday-Friday - Night (7PM - 6AM) 2 - Monday-Friday - Morning Rush Hour (6AM - 9AM) 3 - Monday-Friday - Regular Time (9AM - 3PM) 4 - Monday-Friday - Afternoon Rush Hour (3PM - 7PM) 5 - Weekend (Saturday-Sunday) and Holidays ---------------------------------------------------------- Period of the infraction (1-5): 1 ========================================================== Type of Road 1 - Interstate (Ex. I95) 2 - Federal/State Highway (Ex. US50) 3 - State Road (Ex. TN22, MD410) 4 - County/Local Road (Ex. Randolph Rd, Eusebio Ave, Abena Blvd) or Local - Unknown (Ex. Sterling Str, Garvey Court) ---------------------------------------------------------- Type of road (1-4): 1 ========================================================== Posted Speed Limit: 60 Driving Speed: 120 ========================================================== Types of issues 0 - No particular issues 1 - Health issues 2 - Driving while sleeping 3 - Driving while using an electronic device 4 - Driving under the influence (of alcohol, drugs, intoxicating products, etc) Type of issue (0-4): 3 ========================================================== Type of Traffic Violation 1 - Slow Driving 2 - Fast Driving 3 - Aggressive Driving 4 - Unknown - Other ---------------------------------------------------------- Type of violaction (1-4): 3 ========================================================== Traffic Ticket Summary ---------------------------------------------------------- Period of the day: Monday-Friday - Night (7PM - 6AM) Road Type: Interstate Posted Speed Limit: 60 Driving Speed: 120 Type of Issue: Driving while using an electronic device Base Ticket: 100 Violation Type: Aggressive Driving Addition Fee: 125 ---------------------------------------------------------- Ticket Amount: 225 ========================================================== Press any key to close this window . . .
Combining Cases
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;. 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) { case "TN": taxRate = 1.00; break; case "KY": case "MA": case "NH": taxRate = 5.00; break; case "PA": taxRate = 3.07; break; case "FL": case "NV": case "TX": case "WA": case "WY": taxRate = 0.00; break; case "IN": taxRate = 3.23; break; case "MI": taxRate = 4.25; break; case "CO": taxRate = 4.63; break; case "IL": case "UT": taxRate = 4.95; break; case "NC": taxRate = 5.25; 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("============================================");
Returning from a Conditional Switch
Processing a Switching Return
We have already learned that one way to organize your code is to create functions or methods that each solves a particular problem. One way to make those functions or methods effective is to make them return a value that depends on some conditions. We learned to use if...else conditional statements to perform some validations. The switch statement provides even more controls and options.
In a function, you can create a conditional switch statement, get a value in each case, assign that value to a variable, and then return that value. Here is an example:
using static System.Console; string IdentifyPeriodofDay() { string strPeriod; WriteLine("Periods"); WriteLine("1 - Monday-Friday - Night (7PM - 6AM)"); WriteLine("2 - Monday-Friday - Morning Rush Hour (6AM - 9AM)"); WriteLine("3 - Monday-Friday - Regular Time (9AM - 3PM)"); WriteLine("4 - Monday-Friday - Afternoon Rush Hour (3PM - 7PM)"); WriteLine("5 - Weekend (Saturday-Sunday) and Holidays"); WriteLine("----------------------------------------------------------"); Write("Period of the infraction (1-5): "); int period = int.Parse(ReadLine()); switch (period) { case 1: strPeriod = "Monday-Friday - Night (7PM - 6AM)"; break; default: strPeriod = "Monday-Friday - Regular Time (9AM - 3PM)"; break; case 2: strPeriod = "Monday-Friday - Morning Rush Hour (6AM - 9AM)"; break; case 4: strPeriod = "Monday-Friday - Afternoon Rush Hour (3PM - 7PM)"; break; case 5: strPeriod = "Weekend (Saturday-Sunday) and Holidays"; break; } return strPeriod; } WriteLine("============================================================="); WriteLine("Traffic Tickets System"); WriteLine("============================================================="); string per = IdentifyPeriodofDay(); WriteLine("-------------------------------------------------------------"); WriteLine("Period of the day: {0}", per); WriteLine("=============================================================");
Here is an example of running the program:
============================================================= Traffic Tickets System ============================================================= Periods 1 - Monday-Friday - Night (7PM - 6AM) 2 - Monday-Friday - Morning Rush Hour (6AM - 9AM) 3 - Monday-Friday - Regular Time (9AM - 3PM) 4 - Monday-Friday - Afternoon Rush Hour (3PM - 7PM) 5 - Weekend (Saturday-Sunday) and Holidays ---------------------------------------------------------- Period of the infraction (1-5): 2 ------------------------------------------------------------- Period of the day: Monday-Friday - Morning Rush Hour (6AM - 9AM) ============================================================= Press any key to close this window . . .
Instead of declaring a local variable in the function or method, if the only major operation you are performing on the function/method is to use a switch statement to return a value, you can return the appropriate value in each case. In that case, you don't need a break; statement.
Practical Learning: Processing a Switching Return
using static System.Console; string IdentifyPeriodofDay() { WriteLine("Periods"); WriteLine("1 - Monday-Friday - Night (7PM - 6AM)"); WriteLine("2 - Monday-Friday - Morning Rush Hour (6AM - 9AM)"); WriteLine("3 - Monday-Friday - Regular Time (9AM - 3PM)"); WriteLine("4 - Monday-Friday - Afternoon Rush Hour (3PM - 7PM)"); WriteLine("5 - Weekend (Saturday-Sunday) and Holidays"); WriteLine("----------------------------------------------------------"); Write("Period of the infraction (1-5): "); int period = int.Parse(ReadLine()); switch (period) { case 1: return "Monday-Friday - Night (7PM - 6AM)"; case 2: return "Monday-Friday - Morning Rush Hour (6AM - 9AM)"; default: // case 3: return "Monday-Friday - Regular Time (9AM - 3PM)"; case 4: return "Monday-Friday - Afternoon Rush Hour (3PM - 7PM)"; case 5: return "Weekend (Saturday-Sunday) and Holidays"; } } WriteLine("Traffic Tickets System"); WriteLine("=========================================================="); /* Starting here, a police officer, a government clerk, or a designated * user is used an application on a computer. We want the person * to make selections on the application. * We want to know the period during which the infraction was committed. */ strPeriod = IdentifyPeriodofDay(); WriteLine("==========================================================");
Switching a Selection in a Property Reader
Besides an if condition, you can use a statement, you can use a switch statement to select some values that may match a condition.
Practical Learning: Introducing Condition Statements in Properties
namespace TaxPreparation10 { public class IncomeTax { private string abrv; private string _nm_; private double grsSal; public string Abbreviation { get { return abrv; } set { abrv = value; } } public string StateName { get { switch (abrv) { case "CO": _nm_ = "Colorado"; break; case "FL": _nm_ = "Florida"; break; case "KY": _nm_ = "Kentucky"; break; case "IL": _nm_ = "Illinois"; break; case "IN": _nm_ = "Indiana"; break; case "MA": _nm_ = "Massachusetts"; break; case "MI": _nm_ = "Michigan"; break; case "NC": _nm_ = "North Carolina"; break; case "NH": _nm_ = "New Hampshire"; break; case "NV": _nm_ = "Nevada"; break; case "PA": _nm_ = "Pennsylvania"; break; case "TN": _nm_ = "Tennessee"; break; case "TX": _nm_ = "Texas"; break; case "UT": _nm_ = "Utah"; break; case "WA": _nm_ = "Washington"; break; case "WY": _nm_ = "Wyoming"; break; case "MO": _nm_ = "Missouri"; break; case "MT": _nm_ = "Montana"; break; } return _nm_; } } public double GrossSalary { set { grsSal = value; } get { return grsSal; } } public double TaxAmount { get { double amt = 0.00; switch(abrv) { case "CO": amt = GrossSalary * 4.63 / 100; break; case "FL": case "NV": case "TX": case "WA": case "WY": amt = 0.00; break; case "KY": case "MA": case "NH": amt = GrossSalary * 5.00 / 100; break; case "IL": case "UT": amt = GrossSalary * 4.95 / 100; break; case "IN": amt = GrossSalary * 3.23 / 100; break; case "MI": amt = GrossSalary * 4.25 / 100; break; case "NC": amt = GrossSalary * 5.25 / 100; break; case "PA": amt = GrossSalary * 3.07 / 100; break; case "TN": amt = GrossSalary * 1.00 / 100; break; case "MO": // Missouri if ((GrossSalary >= 0.00) && (GrossSalary <= 106)) { amt = 0.00; } else if ((GrossSalary > 106) && (GrossSalary <= 1_073)) { amt = GrossSalary * 1.50 / 100; } else if ((GrossSalary > 1_073) && (GrossSalary <= 2_146)) { amt = 16 + (GrossSalary * 2.00 / 100); } else if ((GrossSalary > 2_146) && (GrossSalary <= 3_219)) { amt = 37 + (GrossSalary * 2.50 / 100); } else if ((GrossSalary > 3_219) && (GrossSalary <= 4_292)) { amt = 64 + (GrossSalary * 3.00 / 100); } else if ((GrossSalary > 4_292) && (GrossSalary <= 5_365)) { amt = 96 + (GrossSalary * 3.50 / 100); } else if ((GrossSalary > 5_365) && (GrossSalary <= 6_438)) { amt = 134 + (GrossSalary * 4.00 / 100); } else if ((GrossSalary > 6_438) && (GrossSalary <= 7_511)) { amt = 177 + (GrossSalary * 4.50 / 100); } else if ((GrossSalary > 7_511) && (GrossSalary <= 8_584)) { amt = 225 + (GrossSalary * 5.00 / 100); } else // if(GrossSalary > 8_584) { amt = 279 + (GrossSalary * 5.40 / 100); } break; case "MT": /* Montana * https://montana.servicenowservices.com/citizen/kb?id=kb_article_view&sysparm_article=KB0014487 * 2020 Individual Income Tax Rates * If your taxable income is more than but not more than Your tax is minus * $0 $3,100 1% of your taxable income $0 * $3,100 $5,500 2% of your taxable income $31 * $5,500 $8,400 3% of your taxable income $86 * $8,400 $11,300 4% of your taxable income $170 * $11,300 $14,500 5% of your taxable income $283 * $14,500 $18,700 6% of your taxable income $428 * $18,700 6.9% of your taxable income $596 */ if ((GrossSalary >= 0.00) && (GrossSalary <= 3_100)) { amt = (GrossSalary * 1 / 100); } else if ((GrossSalary > 3_100) && (GrossSalary <= 5_500)) { amt = (GrossSalary * 2 / 100) - 31; } else if ((GrossSalary > 5_500) && (GrossSalary <= 8_400)) { amt = (GrossSalary * 3 / 100) - 86; } else if ((GrossSalary > 8_400) && (GrossSalary <= 11_300)) { amt = (GrossSalary * 4 / 100) - 170; } else if ((GrossSalary > 11_300) && (GrossSalary <= 14_500)) { amt = (GrossSalary * 5 / 100) - 283; } else if ((GrossSalary > 14_500) && (GrossSalary <= 18_700)) { amt = (GrossSalary * 6 / 100) - 428; } else // if(grossSalary > 18_700) { amt = (GrossSalary * 6.90 / 100) - 596; } break; } return amt; } } public double NetPay { get { return grsSal - TaxAmount; } } } }
using TaxPreparation10; using static System.Console; IncomeTax tax = new IncomeTax(); WriteLine("=========================================="); WriteLine(" - Amazing DeltaX - State Income Tax -"); WriteLine("=========================================="); 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: "); tax.Abbreviation = ReadLine(); WriteLine("--------------------------------------------"); Write("Gross Salary: "); tax.GrossSalary = double.Parse(ReadLine()); WriteLine("============================================"); WriteLine(" - Amazing DeltaX - State Income Tax -"); WriteLine("--------------------------------------------"); WriteLine($" {tax.StateName}"); WriteLine($"Gross Salary: {tax.GrossSalary:f}"); WriteLine("--------------------------------------------"); WriteLine($"Tax Amount: {tax.TaxAmount:f}"); WriteLine($"Net Pay: {tax.NetPay:f}"); WriteLine("============================================");
========================================== - 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: 6248.85 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- Florida Gross Salary: 6248.85 -------------------------------------------- Tax Amount: 0.00 Net Pay: 6248.85 ============================================ Press any key to close this window . . .
========================================== - 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: NC -------------------------------------------- Gross Salary: 6248.85 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- North Carolina Gross Salary: 6248.85 -------------------------------------------- Tax Amount: 328.06 Net Pay: 5920.79 ============================================ Press any key to close this window . . .
========================================== - 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: MO -------------------------------------------- Gross Salary: 6248.85 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- Missouri Gross Salary: 6248.85 -------------------------------------------- Tax Amount: 383.95 Net Pay: 5864.90 ============================================ Press any key to close this window . . .
========================================== - 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: MT -------------------------------------------- Gross Salary: 6248.85 ============================================ - Amazing DeltaX - State Income Tax - -------------------------------------------- Montana Gross Salary: 6248.85 -------------------------------------------- Tax Amount: 101.47 Net Pay: 6147.38 ============================================ Press any key to close this window . . .
Switching a Tuple
Considering a Tuple for Each Case
Since an item of a tuple primarily holds a value, you can use it in a switching conditional statement. Here is an example:
using static System.Console;
(int memNbr, string name, string category, int fee) member;
member.memNbr = 297_624;
member.name = "Catherine Simms";
member.category = "Senior";
member.fee = -1;
switch (member.category)
{
case "Yound Adult":
member.fee = 15;
break;
case "Adult":
member.fee = 45;
break;
case "Senior":
member.fee = 25;
break;
default:
member.fee = 0;
break;
}
WriteLine("+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=");
WriteLine("Club Membership");
WriteLine("==============================================");
WriteLine("Member Information");
WriteLine("----------------------------------------------");
WriteLine($"Membership #: {member.memNbr}");
WriteLine($"Member Name: {member.name}");
WriteLine($"Membership Type: {member.category}");
WriteLine("----------------------------------------------");
WriteLine($"Membership Fee: {member.fee}");
WriteLine("==============================================");
This would produce:
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= Club Membership ============================================== Member Information ---------------------------------------------- Membership #: 297624 Member Name: Catherine Simms Membership Type: Senior ---------------------------------------------- Membership Fee: 25 ============================================== Press any key to close this window . . .
In reality, because a tuple is some kind of a variable, you can use it as the values to consider in a switch statement. To start, pass the name of the tuple to the parentheses of switch(). Then for each case, provide a complete set of values in parentheses about the tuple. You can then process different cases normally. Here is an example:
using static System.Console; (int number, string name, bool allowedFullTime) member; WriteLine("Enter the values about the employee"); WriteLine("-----------------------------------------------------------------------"); Write("Employee #: "); member.number = int.Parse(ReadLine()); Write("Employee Name: "); member.name = ReadLine(); Write("Is the employee allowed to work full-time (y/n): "); string answer = ReadLine(); switch (answer) { case "y" or "Y": member.allowedFullTime = true; break; default: member.allowedFullTime = false; break; } WriteLine("======================================================================="); WriteLine("Fun Department Store"); WriteLine("Employee Record"); WriteLine("-----------------------------------------------------------------------"); WriteLine($"Employee #: {member.number}"); WriteLine($"Employee Name: {member.name}"); WriteLine($"Full-Time? {member.allowedFullTime}"); WriteLine("-----------------------------------------------------------------------"); switch(member) { case (975_947, "Alex Miller", false): WriteLine("The employee is not allowed to work overtime."); break; case (283_570, "Juliana Schwartz", true): WriteLine("This is a full-time employee who is allowed to work overtime."); break; case (283_624, "Arturo Garcia", true): WriteLine("This iemployee can work full-time."); break; default: WriteLine("The employee is not properly identified."); break; } WriteLine("=======================================================================");
Here is an example of running the program:
Enter the values about the employee ----------------------------------------------------------------------- Employee #: 608624 Employee Name: Arturo Garcia Is the employee allowed to work full-time (y/n): Y ======================================================================= Fun Department Store Employee Record ----------------------------------------------------------------------- Employee #: 608624 Employee Name: Arturo Garcia Full-Time? True ----------------------------------------------------------------------- This employee can work full-time. ======================================================================= Press any key to close this window . . .
Here is another example of running the program:
Enter the values about the employee ----------------------------------------------------------------------- Employee #: 975947 Employee Name: Alex Miller Is the employee allowed to work full-time (y/n): N ======================================================================= Fun Department Store Employee Record ----------------------------------------------------------------------- Employee #: 975947 Employee Name: Alex Miller Full-Time? False ----------------------------------------------------------------------- The employee is not allowed to work overtime. ======================================================================= Press any key to close this window . . .
Here is one more example of running the program:
Enter the values about the employee ----------------------------------------------------------------------- Employee #: 608624 Employee Name: Jules Garcia Is the employee allowed to work full-time (y/n): Not sure ======================================================================= Fun Department Store Employee Record ----------------------------------------------------------------------- Employee #: 608624 Employee Name: Jules Garcia Full-Time? False ----------------------------------------------------------------------- The employee is not properly identified. ======================================================================= Press any key to close this window . . .
Returning a Tuple
We already know that one way to make a function or method produce many values is to make it return a tuple. Based on this, you can create a function that includes a switch statement that returns a value based on a condition that itself produces a tuple. Here is an example:
using static System.Console;
int GetViolation()
{
WriteLine("Type of Traffic Violation");
WriteLine("1 - Slow Driving");
WriteLine("2 - Fast Driving");
WriteLine("3 - Aggressive Driving");
WriteLine("4 - Unknown - Other");
WriteLine("--------------------------------------");
Write("Type of violaction (1-4): ");
return int.Parse(ReadLine());
}
(int abc, string xyz) Evaluate(int problem)
{
(int a, string b) result;
switch (problem)
{
case 1:
result = (0, "Slow Driving");
break;
case 2:
result = (100, "Fast Driving");
break;
case 3:
result = (125, "Aggressive Driving");
break;
default:
result = (50, "Unknown - Other");
break;
}
return result;
}
int infraction = GetViolation();
(int amount, string message) ticket = Evaluate(infraction);
WriteLine("Ticket Summary");
WriteLine("======================================");
WriteLine("Traffic Violation: {0}", ticket.message);
WriteLine("Ticket Amount: {0}", ticket.amount);
As seen with primitive values, instead of using a local tuple variable and assigning a value to it in each case, you can return the necessary value in each case clause. Here is an example:
(int abc, string xyz) Evaluate(int problem) { switch (problem) { case 1: return (0, "Slow Driving"); case 2: return (100, "Fast Driving"); case 3: return (125, "Aggressive Driving"); default: return (50, "Unknown - Other"); } }
Practical Learning: Ending the Lesson
|
|||
Previous | Copyright © 2001-2024, FunctionX | Saturday 29 April 2023, 23:30 | Next |
|