これらのエラーチェックをメソッドに入れるにはどうすればよいですか? ユーザーがプログラムをクラッシュさせることはできません。数値は 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
}
}