如何将`|`操作数应用于字符串? [英] How can I apply the `|` operand to a string?
问题描述
我在这里遇到此行代码的问题...为什么提示我出现此错误?我收到一条错误消息,说操作员'|'不能应用于类型为'bool'和'string'的操作数
如何检查我的驻留变量是否不等于我在if语句中列出的这两个字符串?
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.");
}
}
}
}
推荐答案
您应该在两个条件(而不是值)之间应用它.注意
You should apply it between two conditions, not values. Note
if (residency != "OH" || residency != "MI")
但是请注意,此条件将始终返回 true
.您可能打算使用&&
:
Note, however, that this condition will always return true
. You probably meant to use &&
:
if (residency != "OH" && residency != "MI")
这篇关于如何将`|`操作数应用于字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!