Простая форма калькулятора C # не проверяет правильные операторы? - PullRequest
0 голосов
/ 23 сентября 2018

Я пытаюсь создать форму с использованием C #, похожую на калькулятор.

Мне нужно закодировать метод с именем IsOperator, который проверяет, что переданное ему текстовое поле содержит значение +, -, * или /.

По какой-то причине он не проходит корректную проверку.

Я пытался изменить ||к && и возвращая значения false и true, но ничего не работает.

Когда я пытаюсь поместить в текстовое поле оператора другие вещи, которые не + / - *, результаты превращаются в 0. Ничто не заканчивается проверкой.

Код:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SimpleCalculator
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnCalc_Click(object sender, EventArgs e)
        {
            try
            {
                if (IsValidData())
                {
                    MessageBox.Show("Error");
                } 
                else
                {
                    decimal operand1 = Convert.ToDecimal(txtOperand1.Text);
                    string operator1 = txtOperator.Text;
                    decimal operand2 = Convert.ToDecimal(txtOperand2.Text);

                    decimal result = 0;
                    if (operator1 == "+")
                        result = operand1 + operand2;
                    else if (operator1 == "-")
                        result = operand1 - operand2;
                    else if (operator1 == "*")
                        result = operand1 * operand2;
                    else if (operator1 == "/")
                        result = operand1 / operand2;

                    result = Math.Round(result, 4);
                    txtResult.Text = result.ToString();
                    txtOperand1.Focus();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\n" +
                ex.GetType().ToString() + "\n" +
                ex.StackTrace, "Exception");
            }
        }

        public bool IsValidData()
        {
            return
             //validate the operand1 text box
             IsPresent(txtOperand1, "Operand 1") &&
             IsDecimal(txtOperand1, "Operand 1") &&
             IsWithinRange(txtOperand1, "Operand 1", 0, 1000000) &&

             //validates the operator text box
             IsPresent(txtOperator, "Operator") &&
             IsOperator(txtOperator, "Operator") &&

             //validates the operand 2 text box
             IsPresent(txtOperand2, "Operand 2") &&
             IsDecimal(txtOperand2, "Operand 2") &&
             IsWithinRange(txtOperand2, "Operand 2", 0, 1000000);
        }

        private void btnExit_Click(object sender, System.EventArgs e)
        {
            this.Close();
        }

        //is present
        public bool IsPresent(TextBox textBox, string name)
        {
            if (textBox.Text == "")
            {
                MessageBox.Show(name + " is a required field.", "Entry Error");
                textBox.Focus();
            }
            return false;
        }

        //is decimal
        public bool IsDecimal(TextBox textBox, string name)
        {
            decimal number = 0m;

            if (Decimal.TryParse(textBox.Text, out number))
            {
                return true;
            }
            else
            {
                MessageBox.Show(name + " must be a decimal value.", "Entry Error");
                textBox.Focus();
                return false;
            }
        }

        //is within range
        public bool IsWithinRange(TextBox textBox, string name, decimal min, decimal max)
        {
            decimal number = Convert.ToDecimal(textBox.Text);
            if (number < min || number > max)
            {
                MessageBox.Show(name + "must be between" + min.ToString()
                    + "and" + max.ToString() + ".", "Entry Error");
                textBox.Focus();
                return false;
            }
            return true;
        }

        //is a valid operator
        public bool IsOperator(TextBox textBox, string name)
        {
            string operator1 = "";
            operator1 = Convert.ToString(textBox.Text);
            if (operator1 == "+" && operator1 == "-" && operator1 == "/" && operator1 == "*")
            {
                MessageBox.Show("Please enter a valid operator in the operator text box.", "Entry Error");
                return false;
            }
            return true;
        }

        private void txtOperand1_TextChanged(object sender, EventArgs e)
        {
            this.txtResult.Text = "";
        }

        private void txtOperator_TextChanged(object sender, EventArgs e)
        {
            this.txtResult.Text = "";
        }

        private void txtOperand2_TextChanged(object sender, EventArgs e)
        {
            this.txtResult.Text = "";
        }
    }
}

1 Ответ

0 голосов
/ 24 сентября 2018

Fist of all Вы не должны использовать someString == "" вместо string.IsNullOrEmpty(someString) или string.IsEmptyOrWhitespace(someString). 1

Тогда IsPresent всегда возвращает false.Вы можете изменить этот метод на

public bool IsPresent(TextBox textBox, string name)
{
    if (!string.IsNullOrEmpty(textBox.Text))
    {
         return true;
    }
    MessageBox.Show(name + " is a required field.", "Entry Error");
    textBox.Focus();

    return false;
}

В EventHandler вы забыли ! до IsValidData().Вы показываете ошибку, когда данные действительны, и пытаетесь выполнить расчет, когда ваши данные неверны.

Ваш IsOperator Метод содержит фактически логическую проблему.Вы хотите вернуть true, если оператором является любой из следующих символов +, -, *, \.Поэтому проще перевернуть логику if на что-то подобное, используя LINQ

//is a valid operator
public bool IsOperator(TextBox textBox, string name)
{
    string operator = textBox.Text;
    if (new[] {"+", "-", "*", "/"}.Contains(operator))
    {
         return true;
    }

    MessageBox.Show("Please enter a valid operator in the operator text box.", "Entry Error");

    return false; 
}

. Я думаю, что ваш код также может выиграть от использования Исключений вместо показа MessageBoxes, как только возникает ошибка.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...