问题
The user has to pick 2 number to 1) Add 2) Subtract 3) Multiply 4) Divide 5) Quit. The 2 number that the user entry can be 0-9, a decimal point, or minus sign, and anything else is a error.I need to create a method to check the user entry , by using a true or false Boolean expression. what do I put in the Boolean expression
Console.Write("Enter Number 1: ", num1);
num1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Enter Number 2: ", num2);
num2 = Convert.ToDouble(Console.ReadLine());
if (true)
{
}
switch (input)
{
case 1:
Console.WriteLine("\tResults: {0}", Add(num1, num2));
break;
case 2:
Console.WriteLine("\tResults: {0}", Subtract(num1, num2));
break;
case 3:
Console.WriteLine("\tResults: {0}", Multiply(num1, num2));
break;
case 4:
Console.WriteLine("\tResults: {0}", Divide(num1, num2));
break;
default:
//Console.WriteLine("Invalid Menu Selection.\t Try Again");
//Console.ReadLine();
return;
}
Console.WriteLine("Press any key...");
Console.ReadKey();
Console.Clear();
回答1:
If I understand this correctly, you can use Double.TryParse() to check whether user input is a valid convertible to double string, as well as actually converting it (if the input is valid). For example :
double num1 = 0;
bool isNum1Valid = Double.TryParse(Console.ReadLine(), out num1);
Actually, this question need more context, for example, how you want to use that function and it's signature (parameter type and return type). and showing what have you tried so far.
回答2:
Check that the input is only numbers:
Regex r = new Regex(@"^[-.]?[\d]{1,}[.]{0,1}[\d]{0,}$");
if(r.IsMatch(num1) && r.IsMatch(num2) && num1.Count(j => j == '.') < 2 && num2.Count(j => j == '.') < 2)
{
//Do something
}
And if both numbers are only nums, then use your switch statement.
If the input contains letters, then show some message to the user telling that only numbers are available
来源:https://stackoverflow.com/questions/22433478/a-method-using-boolean-expression