简体   繁体   中英

Bool method keeps returning false

So this code checks to make sure the user has entered a proper math operator in my calculator, but no matter what I seem to do the code ALWAYS gives me false and it's driving me nuts.

if (IsOperator(txtOperator.ToString(), "Operator")




        public bool IsOperator(string textBox, string name)
        {
            switch (textBox)
            {
                case "*":
                    return true;
                case "x":
                    return true;
                case "/":
                    return true;
                case "+":
                    return true;
                case "-":
                    return true;
            }
                MessageBox.Show(name + " must be a valid math operator.", "Entry Error");
                return false;
        }

I think you need txtOperator.Text instead of txtOperator.ToString() in the call to IsOperator , assuming txtOperator is a TextBox.

Have you already debugged the app and inspected the value?

Probably you just need to pass in the the Text property of that textbox...

   if (IsOperator(txtOperator.Text, "Operator")) { ...

The method itself could be optimized to sth like:

    public bool IsOperator(string textEntered, string name)
    {
        switch (textEntered?.Trim())
        {
            case "*":
            case "x":
            case "/":
            case "+":
            case "-":
                return true;

            default:
                MessageBox.Show(name + " must be a valid math operator", "Entry Error");
                return false;

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM