How can I apply the `|` operand to a string?

痞子三分冷 提交于 2020-04-18 00:49:35

问题


I am having trouble with this line of code right here...why am I being prompted with this error? I am getting an error saying "Operator '|' cannot be applied to operands of type 'bool' and 'string' How do check if my residency variable is not equal to these 2 strings I have listed in the if statement?

catch (ArgumentException)
            {
                if (age > 16 | age > 80)
                {
                    Console.WriteLine("You can only enter states of OH or MI ad the driver's age must be between 16 and 80.");
                }
                if (residency != "OH" | "MI")
                {
                    Console.WriteLine("You can only enter states of OH or MI ad the driver's age must be between 16 and 80.");
                }
            }

Here is the full code if you want to get a better idea of what I am trying to execute.

class Program
    {
        static void Main(string[] args)
        {
            CarInsurance create = new CarInsurance();
            Console.Write("Enter the age of the driver: ");
            int age = Convert.ToInt32(Console.ReadLine());
            Console.Write("Enter the state the driver lives in: ");
            string residence = Convert.ToString(Console.ReadLine());
            create.PremiumCalculate(age, residence);
        }
    }
    class CarInsurance
    {
        public int driverAge { get; set; }
        public string residency { get; set; }
        public int totalPremium;

        public int GetPremium()
        {
            return totalPremium;
        }
        public void PremiumCalculate(int age, string residency)
        {
            int premiumOhio = 100;
            int premiumMichigan = 250;
            try
            {
                if (residency == "MI")
                {
                    int total = (100 - age) * 3 + premiumMichigan;
                    Console.WriteLine("Your premium is {0}", total.ToString("C"));
                }
                if (residency == "OH")
                {
                    int total = (100 - age) * 3 + premiumOhio;
                    Console.WriteLine("Your premium is {0}", total.ToString("C"));
                }
            }
            catch (ArgumentException)
            {
                if (age > 16 | age > 80)
                {
                    Console.WriteLine("You can only enter states of OH or MI ad the driver's age must be between 16 and 80.");
                }
                if (residency != "OH" | "MI")
                {
                    Console.WriteLine("You can only enter states of OH or MI ad the driver's age must be between 16 and 80.");
                }
            }
        }
    }

回答1:


You should apply it between two conditions, not values. Note

if (residency != "OH" || residency != "MI")

Note, however, that this condition will always return true. You probably meant to use &&:

if (residency != "OH" && residency != "MI")



回答2:


Let me explain the issue first. Here residency != "OH" | "MI", you are evaluating residency != "OH" and this works and produces bool. Then produced bool fails against | "MI" because operator | is invalid for strings.

If you had 2 strings, you would get

Operator '|' cannot be applied to operands of type 'string' and 'string'

One way to fix it is

using System.Linq;
. . .. 
var exclusionList = new [] {"OH","MI"};
if (!exclusionList.Contains(residency)) 



回答3:


How about something like this. First, I start off by listing all states (yeah, you only care about two of them, but any of them is a valid state):

public enum ResidentState
{
    AL,
    AK,
    AZ,
    AR,
    CA,
    CO,
    CT,
    DE,
    FL,
    GA,
    HI,
    ID,
    IL,
    IN,
    IA,
    KS,
    KY,
    LA,
    ME,
    MD,
    MA,
    MI,
    MN,
    MS,
    MO,
    MT,
    NE,
    NV,
    NH,
    NJ,
    NM,
    NY,
    NC,
    ND,
    OH,
    OK,
    OR,
    PA,
    RI,
    SC,
    SD,
    TN,
    TX,
    UT,
    VT,
    VA,
    WA,
    WV,
    WI,
    WY,
}

Then I start my car insurance class:

class CarInsurance
{
    public int DriverAge { get; private set; }
    public ResidentState Residency { get; private set; }
    public int TotalPremium { get; private set; }

    private bool _ageOk = false;
    private bool _residencyOk = false;
}

It has publicly readable properties for DriverAge, ResidentState and TotalPremium. They can only be set from within the class. It also has a few bookkeeping flags for age and residency validity.

Then, I add a couple of member functions to that class to set the DriverAge and Residency. They do error checking. They both have the same pattern. They will return false unless you set them correctly:

 public bool SetResidency(ResidentState residency)
 {
     if (residency != ResidentState.OH && residency != ResidentState.MI)
     {
         Console.WriteLine("You can only enter states of OH or MI");
         return false;
     }

     Residency = residency;
     _residencyOk = true;
     return true;
 }

 public bool SetDriverAge(int age)
 {
     if (age < 16 || age > 80)
     {
         Console.WriteLine("The driver's age must between 16 and 80.");
         return false;
     }

     _ageOk = true;
     DriverAge = age;
     return true;
 }

If the caller is using these correctly, then _ageOk and _residencyOk will be true. They may be false if not.

Then I create the CalculatePremium function to that class (and a few constants) (note, I renamed it to be verb-noun, I think it makes more sense):

private const int PremiumOhio = 100;
private const int PremiumMichigan = 250;

public int CalculatePremium()
{
    if (!_residencyOk)
    {
        throw new ArgumentException("The driver's residency must first be entered, and only Ohio and Michigan are valid states");
    }

    if (!_ageOk)
    {
        throw new ArgumentException("The driver's age must first be entered, and it must be between 16 and 80");
    }

    int premium;
    switch (Residency)
    {
        case ResidentState.MI:
            premium = PremiumMichigan;
            break;
        case ResidentState.OH:
            premium = PremiumOhio;
            break;
        default:
            premium = 10_000;
            break;
    }

    TotalPremium = (100 - DriverAge) * 3 + premium;
    Console.WriteLine($"Your total premium is {TotalPremium:C}");
    return TotalPremium;
}

Finally, I wrote the Program class that has the Main function:

class Program
{
    static void Main(string[] args)
    {
        CarInsurance insurance = new CarInsurance();
        bool ageOk = false;
        do
        {
            Console.Write("Enter the age of the driver: ");
            var response = Console.ReadLine();
            ageOk = int.TryParse(response, out var age);
            if (!ageOk)
            {
                Console.WriteLine("You must enter an integer for age");
            }
            else
            {
                ageOk = insurance.SetDriverAge(age);
            }
        } while (!ageOk);

        bool stateOk = false;
        do
        {
            Console.Write("Enter the state the driver lives in: ");
            var stateStr = Console.ReadLine();
            stateOk = Enum.TryParse<ResidentState>(stateStr, true, out var state);
            if (!stateOk)
            {
                Console.WriteLine($"The state you entered ({stateStr}) is not a valid two-letter state abbreviation");
            }
            else
            {
                stateOk = insurance.SetResidency(state);
            }

        } while (!stateOk);

        var premium = insurance.CalculatePremium();
    }
}

Note that I check that the entered data is a valid integer (or a valid state abbreviation) in this code. Then I check (using the Insurance class) that it is valid for this calculation. As it's written, it will not cause either of the exceptions within CalculatePremium to be thrown. However, it might make sense to wrap the call to CalculatePremium in a try/catch. I'll leave that up to you - you really need to read up on exceptions.

I wrote this is a way (and explained it in a way), that will allow you to explore some of the features of the language. Step through it in the debugger. Enter invalid entries for both quantities (something that's not an integer, and then something that's out of range for age, and something that's not a state and then not either MI or OH) and see what happens. Try calling calculate premium with invalid values and see what happens (and try to catch the result).



来源:https://stackoverflow.com/questions/61197187/how-can-i-apply-the-operand-to-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!