Hi there,

im new to c# and have been trying to create a calculator without a switch statement, using the operator 'op' as a variable, but i cannot get it to work, here is my current code:

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

namespace Calculator_Neil_04._03._10
{
    public partial class Form1 : Form
    {

        int num1 = 999;
        int num2 = 999;
        int result;
        char op = ' ';
        string num;

        public Form1()
        {
            InitializeComponent();
        }

        public void procnum(char num)//please can you clarify the part in brackets, i.e. meaning
        {
            //op = " ";
            txtbDisplay.Text = num;

            if (op == ' ')  //whats the difference between using ' '  or " "  ??
            {
                num1 = num;
                num1 = Convert.ToInt32(num1);

            }
            else
            {
                num2 = num;
                num2 = Convert.ToInt32(num2);
            }
            
            //System.ComponentModel.Convert.DecimalConverter(op);
            
            //op = Convert.ToDecimal(op);
            result = num1 (op) num2;
            txtbDisplay.Text = result.ToString();
            


        }

        private void btn7_Click(object sender, EventArgs e)
        {
            num = 7;
        }

        public void btn8_Click(object sender, EventArgs e)
        {
            num = 8;
        }

        public void btnPlus_Click(object sender, EventArgs e) //use public or private, not sure?
        {
            op = '+';
        }

        public void btnMinus_Click(object sender, EventArgs e)
        {
            op = '-';
        }

        private void btnMultiply_Click(object sender, EventArgs e)
        {
            op = '*';
        }

        private void btnDivide_Click(object sender, EventArgs e)
        {
            op = '/';
        }



    }
}

Any help would be greatly appreciated - ?

Edited 6 Years Ago by __avd: Added [code] tags. For easy readability, always wrap programming code within posts in [code] (code blocks).

Firstly, you should place code inside [code]

[/code] tags.
Secondly, you cant place the operator in a variable. The compiler reads in the operator when it builds your app. It has no way of knowing what the operator would be so it cant build correclty.
Why did you want to avoid a switch? They are perfectly sound programming structures.

You could build calculator of sorts without one. Simply have 2 textboxes for your 2 input numbers and then use the button event handlers to process the operation but you'd be making life harder for yourself.

Next, the part in brackets in your code defines a method with input parameters. Any time you call the method you have to supply values to fill the parameters defined in the brackets. In your case you have to pass the method a char to fill the variable named num.
The difference between " " and ' ' is that " " is a string literal and ' ' is a char literal. A string is an array of chars. You should avoid using char or string to store numbers. Use int for integer values and double/decimal for numbers with decimal parts.
You should use public for members which will be accessed from outside the class. Generally, event handlers will be used within the class so should be private.

Oh, and welcome to daniweb and the world of C# :)

tags - understood.

+ Thanks for your help, I'm trying to do it without the switch statement and using the operator as a variable as it is something my teacher said i should try to?!

Instead of a switch you could use this:

if (op == '+')
    result = num1 + num2;
else if (op == '-')
    result = num1 - num2;
else if (op == '*')
    result = num1 * num2;
else if (op == '/')
    result = num1 / num2;

That sounds a little odd...you may want to double check that he meant what you think he meant. Unless i've missed something fundamental, you cant put code into a variable. You can store the operator as a variable, but you would still need a switch to check the variable and run a different block of code depending on the operator required...you couldnt do something like

int num1 = 1;
int num2 = 2;
string operator = "+";
int result = num1 operator num2;

It simply wont compile : /

Sorted it anyway - but thanks for your help.

Instead of a switch you could use this:

if (op == '+')
    result = num1 + num2;
else if (op == '-')
    result = num1 - num2;
else if (op == '*')
    result = num1 * num2;
else if (op == '/')
    result = num1 / num2;

Hey lloydy76,

I am stuck up with a problem of a similar sort.
Could you please let me know as to how did you approach to the solution.

Thanks!

Hi,
Came across the thread. Maybe there is a solution. Simple calculator without any conditional statements (switch or if). Try this. Might be big for a beginner ( yet its simple ). The project can be downloaded here.

Concept used: Function call by name

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

namespace SimpleCalc
{
    public partial class SimpleCalc : Form
    {

        public SimpleCalc()
        {
            InitializeComponent();
        }

        public static float Add(float input1, float input2)
        {
            return input1 + input2;
        }

        public static float Subtract(float input1, float input2)
        {
            return input1 - input2;
        }

        public static float Multiply(float input1, float input2)
        {
            return input1 * input2;
        }

        public static float Divide(float input1, float input2)
        {
            return input1 / input2;
        }

        public float InvokeStringMethod(string methodName)
        {
            // Get the Type for the class
            Type calledType = this.GetType();

            // Invoke the method itself. The string returned by the method winds up in s
            float s = (float)calledType.InvokeMember(
                            methodName,
                            BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
                            null,
                            null,
                            new object[] { float.Parse(txtFirstNumber.Text), float.Parse(txtSecondNumber.Text) });

            // Return the string that was returned by the called method.
            return s;
        }

        private void OnCalculateButtonClicked(object sender, EventArgs e)
        {
            float result = InvokeStringMethod(((Button)sender).Text);
            lblResult.Text = String.Format("Result: {0}", result);
        }

    }

}

Hope this helps :)

Edited 4 Years Ago by samsylvestertty

This article has been dead for over six months. Start a new discussion instead.