2013-09-02 3 views
1

Как я могу поместить эти проверки ошибок в метод? Пользователь не может сбой программы, значения числа должны быть от 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 
    } 
} 
+0

Итак, вы хотите, чтобы выполнить проверку на корректность по математике операторов firstNumber и secondNumber в один метод? –

ответ

2

Обычно вы будете использовать Decimal.TryParse для преобразования и вывода сообщения, если номер недействителен. Например:

decimal firstNumber; 
decimal secondNumber; 

if (!decimal.TryParse(txtOperand1.Text, out firstNumber)) 
{ 
    MessageBox.Show("Number is not valid."); 
    return; 
} 
if (firstNumber <= 0 || firstNumber >= 1000000) 
{ 
    MessageBox.Show("Number must be > 0 and < 1000000"); 
    return; 
} 

Вы можете сделать что-то подобное со вторым номером.

Или просто оберните все это методом и позвоните ему, возвратив его bool, чтобы указать, действительны ли числа.

1

Вот мой Подход

private int ValidInput(string operand1, string operand2, string mathSymbol, out decimal firstNumber, out decimal secondNumber out string errorMsg) 
{ 
    int errorCode ; 

    errorMsg = string.Emtpy ; 
    firstNumber = 0 ; 
    secondNumber = 0 ; 

    try 
    { 
     if ((mathSymbol != "/") && (mathSymbol != "*") && (mathSymbol != "+") && (mathSymbol != "-")) 
     { 
      errorCode = 1 ; 
      errorMsg = "ERROR invalid operator"; 
     } 
     else 
     { 
      errorCode = 2 ; 
      firstNumber = Convert.ToDecimal(operand1); 

      if (firstNumber <= 0 || firstNumber >= 1000000) 
      { 
       errorCode = 3 ; 
       errorMsg = "first number must be greater than 0 and less than 1,000,000" ; 
      } 
      else 
      { 
       errorCode = 4 ; 
       secondNumber = Convert.ToDecimal(operand2); 

       if (secondNumber <= 0 || secondNumber >= 1000000) 
       { 
        errorCode = 5 ; 
        errorMsg = "second number must be greater than 0 and less than 1,000,000" ; 
       } 
       else 
       { 
        errorCode = 0; 
       } 
      } 

     } 
    } 
    catch (FormatException fe) 
    { 
     errorMsg = fe.Message ; 
    } 
    catch (OverflowException oe) 
    { 
     errorMsg = oe.Message ; 
    } 
    return errorCode 
} 
private void btnCalculate_Click(object sender, EventArgs e) 
{ 
    decimal firstNumber ; 
    decimal secondNumber ; 
    string mathSymbol = txtOperator.Text; // already a string variable 
    decimal result = 0; 
    int errorCode ; 
      string errorMsg ; 

    errorCode = ValidInput(txtOperand1.Text.Trim(), txtOperand2.Text.Trim(), mathSymbol, out firstNumber, out secondNumber out errorMsg) ; 

    //if there was no error 
    if(errorCode == 0) 
    { 
     //calls the calculate method 
     result = calculate(firstNumber, secondNumber, mathSymbol, result); 

     //you can use the errorCode number to decide which fields to clear or provide more usefull message 
    } 
    else 
    { 
     MessageBox.Show(errorMsg, "ERROR"); 
    } 
} 

Кстати, в сообщении об ошибке вы говорите «1,000.000», но у вас код у вас есть «100000»