8 Replies - 2111 Views - Last Post: 16 December 2010 - 02:40 PM Rate Topic: -----

#1 Guest_badgers*


Reputation:

C# Class Help

Posted 15 December 2010 - 11:13 PM

Hello friends. I have been working with C# for a few weeks now and am enjoying the challenges. I am now working on creating classes.

My objective is to create a new class, Calculate.cs, to do all the calculations for my calculator program.

Here is my 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 SimpleCalculatorProgram
{
    public partial class Form1 : Form
    {
        public int intNumber1;
        private int intNumber2;
        private char chOperator;
        private Calculate calculate;
        private Validator validator;

        public Form1()
        {
            InitializeComponent();
            validator = new Validator();
            calculate = new Calculate();
            btnCalculate.Enabled = false;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtNumber1.Text = String.Empty;
            txtNumber2.Text = String.Empty;
            txtOperator.Text = String.Empty;
            lblResult.Text = String.Empty;
            btnCalculate.Enabled = false;
            txtNumber1.Focus();
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {

            int intResult = 0;

            getUserInput();

            switch (chOperator)
            {
                case '+':
                    intResult = intNumber1 + intNumber2;
                    break;
                case '-':
                    intResult = intNumber1 - intNumber2;
                    break;
                case '*':
                    intResult = intNumber1 * intNumber2;
                    break;
                case '/':
                    intResult = intNumber1 / intNumber2;
                    break;
                default:
                    MessageBox.Show("Incorrect entry; please try again!");
                    break;
            }

            displayResult(intResult);

        }


        private void getUserInput()
        {
            intNumber1 = Convert.ToInt32(txtNumber1.Text);
            intNumber2 = Convert.ToInt32(txtNumber2.Text);
            chOperator = Convert.ToChar(txtOperator.Text);

        }

        private void displayResult(int computedResult)
        {
            lblResult.Text = Convert.ToString(computedResult);
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        //Event handlers created when the textbox property 'CausesValidation' is set to true

        private void txtNumber_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.btnCalculate.Enabled = true;
            String inputText = ((TextBox)sender).Text;
            //Argument below calls the HasInput() method of the Validator class for the
            //object named validator, passing the String value stored in inputText
            if (!validator.HasInput(inputText))
            {
                MessageBox.Show("Please enter a value.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //Cancels the current event handler execution
                e.Cancel = true;
            }
            else
            {
                //Argument below calls the IsNumeric() method of the Validator class for the
                //object named validator, passing the String value stored in the inputText
                if (!validator.IsNumeric(inputText))
                {
                    MessageBox.Show("Please enter an integer.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Cancel = true;
                }
            }
            
        }


        private void txtOperator_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            String inputText = ((TextBox)sender).Text.Trim();

            if (!validator.HasInput(inputText))
            {
                MessageBox.Show("Please enter a value.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                e.Cancel = true;
            }
            else
            {
                if (!validator.IsOperator(inputText))
                {
                    MessageBox.Show("Please enter a valid operator: +,-,*,/.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Cancel = true;
                }
            }
        }



        

    }
}



How do I start to remove the code from the existing code and made the Calculate class? What steps do I make? Are their any good tutorials or helpful readings? Could you provide me with some examples? Could you possibly help me start the code? Any advice would be greatly appreciated!

Thank you very much in advance!

Is This A Good Question/Topic? 0

Replies To: C# Class Help

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4405
  • View blog
  • Posts: 12,262
  • Joined: 18-April 07

Re: C# Class Help

Posted 15 December 2010 - 11:32 PM

Did you realize that you are already in a class? If you look towards the top of your code you will see the line public partial class Form1 : Form. This is saying that you are writing code inside the class called "Form1" which is inherited from the class "Form".

So that is how you are going to start your own class...

public class CalculateClass {
   // Class code goes here
}



You then write methods inside this class to carry out various functions. Let's go ahead and create an add function that adds two values together and returns the result.

public class CalculateClass {
   public int add(int number1, int number2) {
       return (number1 + number2);
   }
}



Now all we have to do to use this function is create an instance of our object and call its add method...

CalculateClass calc = new CalculateClass();
MessageBox.Show("The value of 3 + 5 is: " + calc.add(3,5).ToString());



You can find plenty of tutorials online for C# class building. One that you may find interesting is the one over at aspfree.com. You can find it here...

C# Classes Explained - aspfree.com

As for code that shows how to build a calculator in C# you can also check out the tutorials section here on DIC at the following link...

Basic Calculator in C#

I hope this is enough to get you started. Come back if you have any questions.

:)
Was This Post Helpful? 2
  • +
  • -

#3 Guest_Badgers*


Reputation:

Re: C# Class Help

Posted 16 December 2010 - 11:44 AM

First off, thank you for your post! Here is where I am at now.

Calculate.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleCalculatorProgram
{
    public class Calculate
    {
        public int intNumber1;
        public int intNumber2;
        public char chOperator;

    public Calculate()
    {
    }


    public int calculateResult()
    {
        int intResult = 0;
        switch (chOperator)
        {
            case '+':
                intResult = intNumber1 + intNumber2;
                break;
            case '-':
                intResult = intNumber1 - intNumber2;
                break;
            case '*':
                intResult = intNumber1 * intNumber2;
                break;
            case '/':
                intResult = intNumber1 / intNumber2;
                break;
            default:
                Console.WriteLine("Incorrect entry; please try again!");
                break;
        }
        return intResult;
    }
   }
}



Form1.cs

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 SimpleCalculatorProgram
{
    public partial class Form1 : Form
    {
        public int intNumber1;
        private int intNumber2;
        private char chOperator;
        private Calculate calculate;
        private Validator validator;

        public Form1()
        {
            InitializeComponent();
            validator = new Validator();
            calculate = new Calculate();
            btnCalculate.Enabled = false;
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            txtNumber1.Text = String.Empty;
            txtNumber2.Text = String.Empty;
            txtOperator.Text = String.Empty;
            lblResult.Text = String.Empty;
            btnCalculate.Enabled = false;
            txtNumber1.Focus();
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {

            int intResult = 0;

            getUserInput();

            

            displayResult(intResult);

        }


        private void getUserInput()
        {
            intNumber1 = Convert.ToInt32(txtNumber1.Text);
            intNumber2 = Convert.ToInt32(txtNumber2.Text);
            chOperator = Convert.ToChar(txtOperator.Text);

        }

        private void displayResult(int computedResult)
        {
            lblResult.Text = Convert.ToString(computedResult);
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        //Event handlers created when the textbox property 'CausesValidation' is set to true

        private void txtNumber_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.btnCalculate.Enabled = true;
            String inputText = ((TextBox)sender).Text;
            //Argument below calls the HasInput() method of the Validator class for the
            //object named validator, passing the String value stored in inputText
            if (!validator.HasInput(inputText))
            {
                MessageBox.Show("Please enter a value.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //Cancels the current event handler execution
                e.Cancel = true;
            }
            else
            {
                //Argument below calls the IsNumeric() method of the Validator class for the
                //object named validator, passing the String value stored in the inputText
                if (!validator.IsNumeric(inputText))
                {
                    MessageBox.Show("Please enter an integer.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Cancel = true;
                }
            }

        }


        private void txtOperator_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            String inputText = ((TextBox)sender).Text.Trim();

            if (!validator.HasInput(inputText))
            {
                MessageBox.Show("Please enter a value.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                e.Cancel = true;
            }
            else
            {
                if (!validator.IsOperator(inputText))
                {
                    MessageBox.Show("Please enter a valid operator: +,-,*,/.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Cancel = true;
                }
            }
        }





    }
}




This compiles with no errors. I get 0 to any result. I know that's because I set intResult to 0 and display it in btnCalculate and displayResult. How do I get the results from Calculate.cs?

MOD EDIT: You use CODE tags to post code, NOT QUOTE tags!

:code:

This post has been edited by JackOfAllTrades: 16 December 2010 - 12:04 PM

Was This Post Helpful? 0

#4 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6092
  • View blog
  • Posts: 23,612
  • Joined: 23-August 08

Re: C# Class Help

Posted 16 December 2010 - 12:08 PM

You need to go read the links Martyr2 gave you. Thoroughly. You have created a Calculate object. You now need to set the member variables of that object and call the calculateResult() method of the object to get your result. This is really basic stuff here.
Was This Post Helpful? 0
  • +
  • -

#5 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1253
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: C# Class Help

Posted 16 December 2010 - 12:18 PM

Notice how chOperator is used for the switch yet you never set it to anything. ;)
Was This Post Helpful? 0
  • +
  • -

#6 Guest_Badgers*


Reputation:

Re: C# Class Help

Posted 16 December 2010 - 12:20 PM

View PostJackOfAllTrades, on 16 December 2010 - 11:08 AM, said:

You need to go read the links Martyr2 gave you. Thoroughly. You have created a Calculate object. You now need to set the member variables of that object and call the calculateResult() method of the object to get your result. This is really basic stuff here.


Thank you. I have made some changes, but I am having troubles still. Thank you for bearing with me. I feel like I am making progress after doing some reading.

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 SimpleCalculatorProgram
{
    public partial class Form1 : Form
    {
        public int intNumber1;
        private int intNumber2;
        private char chOperator;
        private Calculate obj;
        private Calculate calculate;
        private Validator validator;

        public Form1()
        {
            InitializeComponent();
            validator = new Validator();
            calculate = new Calculate();
            btnCalculate.Enabled = false;
            obj.intNumber1 = 5;
            obj.intNumber2 = 10;
            obj.chOperator = '+';

        }
        private void btnClear_Click(object sender, EventArgs e)
        {
            txtNumber1.Text = String.Empty;
            txtNumber2.Text = String.Empty;
            txtOperator.Text = String.Empty;
            lblResult.Text = String.Empty;
            btnCalculate.Enabled = false;
            txtNumber1.Focus();
        }

        private void btnCalculate_Click(object sender, EventArgs e)
        {

            int intResult = obj.Calculate();

            getUserInput();

            displayResult(intResult);

        }


        private void getUserInput()
        {
            intNumber1 = Convert.ToInt32(txtNumber1.Text);
            intNumber2 = Convert.ToInt32(txtNumber2.Text);
            chOperator = Convert.ToChar(txtOperator.Text);

        }

        private void displayResult(int computedResult)
        {
            lblResult.Text = Convert.ToString(computedResult);
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        //Event handlers created when the textbox property 'CausesValidation' is set to true

        private void txtNumber_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.btnCalculate.Enabled = true;
            String inputText = ((TextBox)sender).Text;
            //Argument below calls the HasInput() method of the Validator class for the
            //object named validator, passing the String value stored in inputText
            if (!validator.HasInput(inputText))
            {
                MessageBox.Show("Please enter a value.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //Cancels the current event handler execution
                e.Cancel = true;
            }
            else
            {
                //Argument below calls the IsNumeric() method of the Validator class for the
                //object named validator, passing the String value stored in the inputText
                if (!validator.IsNumeric(inputText))
                {
                    MessageBox.Show("Please enter an integer.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Cancel = true;
                }
            }

        }


        private void txtOperator_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            String inputText = ((TextBox)sender).Text.Trim();

            if (!validator.HasInput(inputText))
            {
                MessageBox.Show("Please enter a value.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                e.Cancel = true;
            }
            else
            {
                if (!validator.IsOperator(inputText))
                {
                    MessageBox.Show("Please enter a valid operator: +,-,*,/.", "Invalid Input", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Cancel = true;
                }
            }
        }





    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleCalculatorProgram
{
    public class Calculate
    {
        public int intNumber1;
        public int intNumber2;
        public int intResult = 0;
        public char chOperator;

        public Calculate()
        {
        }


        public int calculateResult()
        {
            switch (chOperator)
            {
                case '+':
                    intResult = intNumber1 + intNumber2;
                    break;
                case '-':
                    intResult = intNumber1 - intNumber2;
                    break;
                case '*':
                    intResult = intNumber1 * intNumber2;
                    break;
                case '/':
                    intResult = intNumber1 / intNumber2;
                    break;
                default:
                    Console.Write("Incorrect entry; please try again!");
                    break;
            }
            return intResult;
        }
    }
}

Was This Post Helpful? 0

#7 Guest_Badgers*


Reputation:

Re: C# Class Help

Posted 16 December 2010 - 12:22 PM

Error: Error 'SimpleCalculatorProgram.Calculate' does not contain a definition for 'Calculate' and no extension method 'Calculate' accepting a first argument of type 'SimpleCalculatorProgram.Calculate' could be found (are you missing a using directive or an assembly reference?)

Warning: Warning 1 Field 'SimpleCalculatorProgram.Form1.obj' is never assigned to, and will always have its default value null
Was This Post Helpful? 0

#8 Robin19  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 272
  • View blog
  • Posts: 552
  • Joined: 07-July 10

Re: C# Class Help

Posted 16 December 2010 - 02:15 PM

Error 'Scp.Calculate' does not contain a definition for 'Calculate'
This line means that you are trying to call a method called Calculate() from the class called Calculate. There is no method. You do have a method called CalculateResult(). So change obj.Calculate() to obj.CalculateResult().
Was This Post Helpful? 0
  • +
  • -

#9 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6092
  • View blog
  • Posts: 23,612
  • Joined: 23-August 08

Re: C# Class Help

Posted 16 December 2010 - 02:40 PM

Except that there is no valid obj.

Why did you create a new Calculate variable named obj here?
private Calculate obj;
private Calculate calculate;


when you had one called calculate which you correctly instantiate here:
calculate = new Calculate();

and then you try to use the new, uninstantiated one right after:
obj.intNumber1 = 5;
obj.intNumber2 = 10;
obj.chOperator = '+';


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1