如何将这些错误检查放入方法中?用户不能使程序崩溃,数值必须在 0 到 1,000,000 之间。这就是我到目前为止所拥有的。
如果有一个空字段,则必须有一条错误消息说:请输入缺少的字段。
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
// changes value that is in text box and switches it into a decimal
decimal firstNumber = Convert.ToDecimal(txtOperand1.Text);
decimal secondNumber = Convert.ToDecimal(txtOperand2.Text);
string mathSymbol = txtOperator.Text; // already a string variable
decimal result = 0;
//calls the method
result = calculate(firstNumber, secondNumber, mathSymbol, result);
if (mathSymbol != "/" && mathSymbol != "*" && mathSymbol != "+" && mathSymbol != "-")
{
txtOperator.Text = "";
MessageBox.Show("ERROR invalid operator");
}
if (firstNumber <= 0 || firstNumber >= 100000 || secondNumber <= 0 || secondNumber >= 1000000)
{
txtResult.Text = "";
MessageBox.Show("Numbers must be greater than 0 and less than 1,000,000");
txtOperand1.Text = "";
txtOperand2.Text = "";
txtOperator.Text = "";
}
}
catch (FormatException)
{
MessageBox.Show("Please enter values.", "ERROR");
}
catch (Exception op)
{
MessageBox.Show(op.Message, "ERROR");
}
}
// method calculate - amount = to calculate then calculate = to result
private decimal calculate(decimal num1, decimal num2, string symbol, decimal amount)
{
if (symbol == "+") // checks if user enters a + then adds numbers
amount = num1 + num2;
else if (symbol == "-") // checks if user enters a - then minus numbers
amount = num1 - num2;
else if (symbol == "*") // checks if user enters a * then multiplies numbers
amount = num1 * num2;
else if (symbol == "/") // checks if user enters a / then divides numbers
amount = num1 / num2;
txtResult.Text = amount.ToString("f4");
return amount;
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close(); // closes the form if exit button is pressed
}
private void clearResult(object sender, EventArgs e)
{
txtResult.Text = " "; // clears results if txtOperand1 is changed
}
private void clear_result(object sender, EventArgs e)
{
txtResult.Text = " "; // clears results if txtOperator is changed
}
private void ClearResults3(object sender, EventArgs e)
{
txtResult.Text = " "; // clears results if txtOperand2 is changed
}
}