1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Development c# - calculator that should be working

Discussion in 'Software' started by Journeyer, 12 Feb 2013.

  1. Journeyer

    Journeyer Minimodder

    Joined:
    31 Aug 2006
    Posts:
    3,039
    Likes Received:
    99
    So, I am in the process of learning C# (through a proper course no less), and I have a "paper" to return soon which involves coding a functional basic calculator. Now, I think I have the code worked out but for some reason it only returns the value of "0". I've been tinkering, staring at, swearing at and just plain old pounding my head against it for the last few evenings, but still I haven't figured out what's wrong with it.

    Therefore I turn to the vast repository of knowledge that is bit-tech in the hopes that someone might be able to point me in the right direction.

    Here is my code:

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Text;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    
    public partial class _Default : System.Web.UI.Page
    {
        public double total1 = 0;
        public double total2 = 0;
    
        bool plusButtonClick = false;
        bool minusButtonClick = false;
        bool multiplyButtonClick = false;
        bool divideButtonClick = false;
    
        public void Page_Load(object sender, EventArgs e)
        {
            Button1.Click += new EventHandler(numberClick);
            Button2.Click += new EventHandler(numberClick);
            Button3.Click += new EventHandler(numberClick);
            Button4.Click += new EventHandler(numberClick);
            Button5.Click += new EventHandler(numberClick);
            Button6.Click += new EventHandler(numberClick);
            Button7.Click += new EventHandler(numberClick);
            Button8.Click += new EventHandler(numberClick);
            Button9.Click += new EventHandler(numberClick);
            Button10.Click += new EventHandler(numberClick);    
        }
    
        public void numberClick(object sender, EventArgs e)
        {
            Button ButtonThatWasPushed = (Button)sender;
            calculationBox.Text += ButtonThatWasPushed.Text;
        }
    
        public void clearClick(object sender, EventArgs e)
        {
            calculationBox.Text = String.Empty;
        }
    
        public void plusClick(object sender, EventArgs e)
        {
            plusButtonClick = true;
            minusButtonClick = false;
            multiplyButtonClick = false;
            divideButtonClick = false;
    
            total1 = System.Double.Parse(calculationBox.Text);
            calculationBox.Text = String.Empty;
        }
    
        public void minusClick(object sender, EventArgs e)
        {
            total1 += double.Parse(calculationBox.Text);
            calculationBox.Text = String.Empty;
            plusButtonClick = false;
            minusButtonClick = true;
            multiplyButtonClick = false;
            divideButtonClick = false;
        }
    
        public void multiplyClick(object sender, EventArgs e)
        {
            total1 += double.Parse(calculationBox.Text);
            calculationBox.Text = String.Empty;
            plusButtonClick = false;
            minusButtonClick = false;
            multiplyButtonClick = true;
            divideButtonClick = false;
        }
    
        public void divideClick(object sender, EventArgs e)
        {
            total1 += double.Parse(calculationBox.Text);
            calculationBox.Text = String.Empty;
            plusButtonClick = false;
            minusButtonClick = false;
            multiplyButtonClick = false;
            divideButtonClick = true;
        }
    
        public void equalClick(object sender, EventArgs e)
        {
            if (plusButtonClick == true)
            {
                total2 = total1 + double.Parse(calculationBox.Text);
            }
            else if (minusButtonClick == true)
            {
                total2 = total1 - double.Parse(calculationBox.Text);
            }
            else if (multiplyButtonClick == true)
            {
                total2 = total1 * double.Parse(calculationBox.Text);
            }
            else if (divideButtonClick == true)
            {
                total2 = total1 / double.Parse(calculationBox.Text);
            }
            calculationBox.Text = total2.ToString();
            total1 = 0;
        }
    }
     
    Last edited: 13 Feb 2013
  2. Daedelus

    Daedelus What's a Dremel?

    Joined:
    7 May 2009
    Posts:
    253
    Likes Received:
    12
    Have you stepped through your code to see what the flow actually is?

    Put a breakpoint in the Page_Load method and see what happens when you click on various buttons.

    My guess is that your calculation event handlers are never being called. Where do you add event handlers to the +, -, / and * button click events?
     
  3. Journeyer

    Journeyer Minimodder

    Joined:
    31 Aug 2006
    Posts:
    3,039
    Likes Received:
    99
    The calculation events are called through element IDs in the webform (I didn't code eventhandlers for these - might be a mistake. I'll try building eventhandlers for these as well), and the whole program is supposed to run in a webform. I will try a few well-placed breakpoints to see if they can help illuminate the problems. Right now it doesn't seem like my variables are actually grabbing any data for some reason...
     
  4. ferret141

    ferret141 Minimodder

    Joined:
    18 Oct 2010
    Posts:
    1,314
    Likes Received:
    40
    Use the
    Code:
     forum tags. It should keep your code formatting.
     
  5. Journeyer

    Journeyer Minimodder

    Joined:
    31 Aug 2006
    Posts:
    3,039
    Likes Received:
    99
     
    Last edited: 13 Feb 2013
  6. theshadow2001

    theshadow2001 [DELETE] means [DELETE]

    Joined:
    3 May 2012
    Posts:
    5,284
    Likes Received:
    183
    Is there no way to monitor your variables? For example when you run the code and you press the plus button, does the value actually get moved from whatever box into the total1 variable before its cleared. Does total2 receive a value when you press equals etc. Use break points and monitor your variables. Keep moving through the program until you find where its not working as expected.

    I dunno maybe that sort of nebulous advice isn't much use. :/

    Edit: ninja'd by your own edit, your getting the hang of the debugging now though :thumb:

    Another thing I like to do, especially when I am unsure of how a function is going to work, I prototype it separately to the main code. So rather than putting it in and try to debug the whole piece of code, I set up a snippet on its own and run that and adjust until I get the desired result then add it in to the actual code knowing that I should have it right.

    Perhaps you could do this with the calculation box and your variable
     
    Last edited: 13 Feb 2013
  7. Journeyer

    Journeyer Minimodder

    Joined:
    31 Aug 2006
    Posts:
    3,039
    Likes Received:
    99
    Hehehe, yes, but thank you for your input - trust me, it is highly appreciated.
    I'm quite new to this (as I'm sure you've figured), and I'm learning new things every day I sit down to tinker with it. But still I am unable to figure out why my variables doesn't grab any data. I can see that the button events are registered, that the calculationBox element receives the values clicked, but the values does not get transferred to the total1 variable (not to mention the total2 variable).
     
  8. Jester_612

    Jester_612 "Jammy..."

    Joined:
    14 Nov 2011
    Posts:
    1,139
    Likes Received:
    30
    Being a simpleton, I don't get why you've not registered the other actions.
    Code:
    (...)
    Button9.Click += new EventHandler(numberClick);
    Button10.Click += new EventHandler(numberClick);
    ButtonPlus.Click += new EventHandler(plusClick); //etc
    (...)
     
  9. Journeyer

    Journeyer Minimodder

    Joined:
    31 Aug 2006
    Posts:
    3,039
    Likes Received:
    99
    Well, I thought that calling the calculation functions through element IDs would be simpler, but I am coding eventhandlers for calculation now to see if that solves the problem.

    Edit: I'm still having the same problem, though now i have built eventhandlers for calculation and I have incorporated switch statements to replace the if-else statements used earlier. Here's my current code that still returns a value of "0". The difference is that now I know that my variables "total1" and "calc" collects a value, but this value doesn't seem to be passed along for calculation when I hit the "equals" button. Argh! Will the headache never end? :wallbash:

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Text;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    
    public partial class _Default : System.Web.UI.Page
    {
        int total1 = 0;
        int total2 = 0;
        string calc;
    
        public void Page_Load(object sender, EventArgs e)
        {
            Button1.Click += new EventHandler(numberClick);
            Button2.Click += new EventHandler(numberClick);
            Button3.Click += new EventHandler(numberClick);
            Button4.Click += new EventHandler(numberClick);
            Button5.Click += new EventHandler(numberClick);
            Button6.Click += new EventHandler(numberClick);
            Button7.Click += new EventHandler(numberClick);
            Button8.Click += new EventHandler(numberClick);
            Button9.Click += new EventHandler(numberClick);
            Button10.Click += new EventHandler(numberClick);
            Plus.Click += new EventHandler(calculationClick);
            Minus.Click += new EventHandler(calculationClick);
            Multiply.Click += new EventHandler(calculationClick);
            Divide.Click += new EventHandler(calculationClick);
        }
                                                                       
        public void numberClick(object sender, EventArgs e)
        {
            Button ButtonThatWasPushed = (Button)sender;
            calculationBox.Text += ButtonThatWasPushed.Text;
        }
    
        public void calculationClick(object sender, EventArgs e)
        {
            Button calculationThatWasSelected = (Button)sender;
            total1 += int.Parse(calculationBox.Text);
            calc = calculationThatWasSelected.Text;
            calculationBox.Text = string.Empty;
        }
    
        public void equalClick(object sender, EventArgs e)
        {
            switch (calc)
            {
                case "+":
                    total2 = total1 + int.Parse(calculationBox.Text);
                    break;
                case "-":
                    total2 = total1 - int.Parse(calculationBox.Text);
                    break;
                case "*":
                    total2 = total1 * int.Parse(calculationBox.Text);
                    break;
                case "/":
                    if (calculationBox.Text == "0")
                    {
                        test.InnerHtml = "You can't divide by zero! Seriously; don't! You will bring doom upon us all!";
                    }
                    else if (int.Parse(calculationBox.Text) > 0)
                    {
                        total2 = total1 / int.Parse(calculationBox.Text);
                    }
                    break;
                default:
                    total2 = 0;
                    break;
            }
            
            test.InnerHtml = total2.ToString();
            total1 = 0;
        }
    
        public void clearClick(object sender, EventArgs e)
        {
            calculationBox.Text = String.Empty;
        }
    }
     
    Last edited: 13 Feb 2013
  10. Jester_612

    Jester_612 "Jammy..."

    Joined:
    14 Nov 2011
    Posts:
    1,139
    Likes Received:
    30
    I was looking at the switch and just going "no way, strings!"

    Does clearClick do the job/get called then?
     
  11. Journeyer

    Journeyer Minimodder

    Joined:
    31 Aug 2006
    Posts:
    3,039
    Likes Received:
    99
    Yes clearclick works.
    Do you have another option than strings?

    I am sure there are more elegant ways of doing this, but as of now I do not know of any (I'm still a C# noob after all) so any pointers are greatly appreciated.
     
  12. Jester_612

    Jester_612 "Jammy..."

    Joined:
    14 Nov 2011
    Posts:
    1,139
    Likes Received:
    30
    I don't know much about C# either, it's just I was used to the idea that switches were int only.

    Well err, I can't help anymore then, because my line of thinking is with something a bit older.
     
  13. Plugs

    Plugs Minimodder

    Joined:
    5 Nov 2009
    Posts:
    528
    Likes Received:
    64
    My knowledge is more of Java, but I hear C# is similar, so the below should be possible in the language in some form (hopefully C# doesn't make it even more complicated), though it may be too advanced depending on how far you are into your learning.

    Indeed, your best bet is to probably ignore the rest of this post if you haven't been taught this yet.

    If you are feeling adventurous you could create an interface which dictates a method "calculate", then subclass button (and implement your interface) for each of your maths operators, in the event handlers you set the interface to the specific subclass. In the calculate method you just call selectedFunction.calculate(total1, parseInt(calculationText)

    rough non c# code:
    Code:
    //note this interface only applies to binary functions at the moment
    interface MathFunction{
    
        double calculate(int input1, int input2);
    
    }
    
    class plusButton subclasses Button implements MathFunction {
    
        double calculate(int input1, int input2){
            return input1 + input2;
        }
    }
    //etc for other buttons
    
    
    //altering your code
    MathFunction selectedFunction;
    
     public void calculationClick(object sender, EventArgs e)
        {
            selectedFunction = (MathFunction) sender;
    
            total1 += int.Parse(calculationBox.Text);
            calculationBox.Text = string.Empty;
        }
    
        public void equalClick(object sender, EventArgs e){
            double result = selectFunction.calculate(total1, parseInt(calculationBox.text);
             //do what you want with result...
        }
    
    With a few word changes, the above would work in Java... though again this code isn't C# and thus may need to be completely changed to work.
     
  14. Journeyer

    Journeyer Minimodder

    Joined:
    31 Aug 2006
    Posts:
    3,039
    Likes Received:
    99

    Hmm, interesting.
    I think I'm vaguely able to see what's going on there, so I might give it a go tonight (provided the missus does let me go - it's valentine's after all, and she likes that kind of thing) as I'm at work currently.
     
  15. heh-

    heh- curses.

    Joined:
    31 May 2007
    Posts:
    186
    Likes Received:
    11
    without actually running your code (so I could be wrong), I think your problem is with postback.

    Each time you click on a button on the page, the browser posts back to the server esentially creating a new class each time a button on the page is pressed - it doesn't know that you've called the class before, or that it's the same class as before. This is why your variables are always 0.

    The controls on the page (the textboxes for example) keep the value set to them in the page, so their values are saved between button clicks.

    A good way to hold your variable values is to use ViewState which writes the value into the html each time the page reloads.

    If you do a windows forms application, it doesn't have this problem as there is no separation between client and server - so this code would work if it was in a windows app.


    tldr;

    Look into holding your public variables in ViewState to keep their values between postbacks.
     
    Journeyer likes this.
  16. Journeyer

    Journeyer Minimodder

    Joined:
    31 Aug 2006
    Posts:
    3,039
    Likes Received:
    99
    Oh!
    Oh by the FSM - you're right!
    I forgot all about postback, and I haven't granted it a single thought!

    Thank you so much heh-, I won't know if that truly is the problem until I get a chance to test it, but I am now quite certain that it is. Thank you - you may very well have saved my sanity. Rep granted.
     
  17. BentAnat

    BentAnat Software Dev

    Joined:
    26 Jun 2008
    Posts:
    7,230
    Likes Received:
    219
    Beaten to it by that.

    C# on the web is a bit strange because it's all code-behind, so you need to check your postbacks carefully.
     
  18. Journeyer

    Journeyer Minimodder

    Joined:
    31 Aug 2006
    Posts:
    3,039
    Likes Received:
    99
    Again, thank you heh_.
    I may be a bit late, but your tip on viewstate saved my work (not to mention my skull from repeated impacts with a hard brick wall). My code now works beautifully (though I did rewrite it extensively), and I have submitted my work. Thank you for your help.
     

Share This Page