Sign in to follow this  
GraySnakeGenocide

Building a calculator in C#, stuck on doing the math stuff.

Recommended Posts

[source lang="csharp"]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
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private Boolean lastCharIsSymbol { get; set; }

int number;

bool add = false;
bool subtract = false;
bool multiply = false;
bool divide = false;

private void button0_Click(object sender, EventArgs e)
{
number = 0;
textBox1.Text += number.ToString();
lastCharIsSymbol = false;
}

private void button1_Click(object sender, EventArgs e)
{
number = 1;
textBox1.Text += number.ToString();
lastCharIsSymbol = false;
}

private void button2_Click(object sender, EventArgs e)
{
number = 2;
textBox1.Text += number.ToString();
lastCharIsSymbol = false;
}

private void button3_Click(object sender, EventArgs e)
{
number = 3;
textBox1.Text += number.ToString();
lastCharIsSymbol = false;
}

private void button4_Click(object sender, EventArgs e)
{
number = 4;
textBox1.Text += number.ToString();
lastCharIsSymbol = false;
}

private void button5_Click(object sender, EventArgs e)
{
number = 5;
textBox1.Text += number.ToString();
lastCharIsSymbol = false;
}

private void button6_Click(object sender, EventArgs e)
{
number = 6;
textBox1.Text += number.ToString();
lastCharIsSymbol = false;
}

private void button7_Click(object sender, EventArgs e)
{
number = 7;
textBox1.Text += number.ToString();
lastCharIsSymbol = false;
}

private void button8_Click(object sender, EventArgs e)
{
number = 8;
textBox1.Text += number.ToString();
lastCharIsSymbol = false;
}

private void button9_Click(object sender, EventArgs e)
{
number = 9;
textBox1.Text += number.ToString();
lastCharIsSymbol = false;
}

private void buttonPlus_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || lastCharIsSymbol)
return;
else
{
add = true;
textBox1.Text += " + ";
lastCharIsSymbol = true;
}
}

private void buttonMinus_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || lastCharIsSymbol)
return;
else
{
subtract = true;
textBox1.Text += " - ";
lastCharIsSymbol = true;
}
}

private void buttonMultiply_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || lastCharIsSymbol)
return;
else
{
multiply = true;
textBox1.Text += " * ";
lastCharIsSymbol = true;
}
}

private void buttonDivide_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || lastCharIsSymbol)
return;
else
{
divide = true;
textBox1.Text += " / ";
lastCharIsSymbol = true;
}

}

private void buttonEquals_Click(object sender, EventArgs e)
{
if (add)
{

}

if (subtract)
{

}

if (multiply)
{

}

if (divide)
{

}
}

private void buttonClear_Click(object sender, EventArgs e)
{
textBox1.Text = String.Empty;
}
}
}
[/source]


What I want to do, is be able to use more than 2 numbers together in the one textbox.

For example, I want to be able to do like, 14 + 86 - 24, etc.

How do I go about doing this? If I had 2 textboxes it would seemingly be easy storing the values placed in them in 2 seperate ints. But since I want to be able to use more than 2 numbers how do I do this?

And for the record, this is a self-teaching project, not schoolwork.

Sorry if this is simple stuff/straight forward, my brains bunched up lately. Edited by Bill Fountaine

Share this post


Link to post
Share on other sites
kunos    2254
honestly I don't understand the point of threads like these.
I mean, what are you looking for? A solution? How being given a solution would make you improve? Programming is all about finding solutions to problems. If somebody just gives you the solution you'll be back asking another solution for your next problem and you won't learn anything.

You are looking for an hint? Here's one: break down your problem into simple parts, start from a simple case were you are making assumptions.. ie, assume you'll have a sequence of number operation number operation and you solve it left to right without any operation precedence.
Look how to get a string and split this into parts, C# strings are very good at this.
Once you get it done you might look into more complex stuff, operator precedence, brackets and so on.. this usually involves a creation of a tree of operation that is then solved into a solution.

You mentioned you've been programming for 4 years. .I dont mean any offense, but if after 4 years you're stuck at this, maybe you should consider the possibility that perhaps programming isn't what you were born to do?

Share this post


Link to post
Share on other sites
[quote name='kunos' timestamp='1341001767' post='4954076']
honestly I don't understand the point of threads like these.
I mean, what are you looking for? A solution? How being given a solution would make you improve? Programming is all about finding solutions to problems. If somebody just gives you the solution you'll be back asking another solution for your next problem and you won't learn anything.

You are looking for an hint? Here's one: break down your problem into simple parts, start from a simple case were you are making assumptions.. ie, assume you'll have a sequence of number operation number operation and you solve it left to right without any operation precedence.
Look how to get a string and split this into parts, C# strings are very good at this.
Once you get it done you might look into more complex stuff, operator precedence, brackets and so on.. this usually involves a creation of a tree of operation that is then solved into a solution.

You mentioned you've been programming for 4 years. .I dont mean any offense, but if after 4 years you're stuck at this, maybe you should consider the possibility that perhaps programming isn't what you were born to do?
[/quote]

or maybe I've just been too lazy to actually PROGRAM instead of just reading constantly?

It's not like I'm not understanding anything. I've just been approaching it wrong.

Why do some people have to come across as such snobs.

Share this post


Link to post
Share on other sites
[quote name='boogyman19946' timestamp='1341002263' post='4954081']
I think Telastyn meant that instead of storing your input as a single string, you can keep the input separated and THEN to display it you can construct the string from the input.
[/quote]

I'm just not quite sure on how to do this stuff. Dealing with 2 numbers would be easy, but multiple is sketchy for me.

Share this post


Link to post
Share on other sites
I think what you are looking for is a [url="http://en.wikipedia.org/wiki/Binary_expression_tree"]Binary Expression Tree[/url].You also might want to look into syntax trees. These do exactly what your looking to do.... Edited by DevLiquidKnight

Share this post


Link to post
Share on other sites
Slateboard    213
[quote name='kunos' timestamp='1341001767' post='4954076']
honestly I don't understand the point of threads like these.
I mean, what are you looking for? A solution? How being given a solution would make you improve? Programming is all about finding solutions to problems. If somebody just gives you the solution you'll be back asking another solution for your next problem and you won't learn anything.

You are looking for an hint? Here's one: break down your problem into simple parts, start from a simple case were you are making assumptions.. ie, assume you'll have a sequence of number operation number operation and you solve it left to right without any operation precedence.
Look how to get a string and split this into parts, C# strings are very good at this.
Once you get it done you might look into more complex stuff, operator precedence, brackets and so on.. this usually involves a creation of a tree of operation that is then solved into a solution.

You mentioned you've been programming for 4 years. .I dont mean any offense, but if after 4 years you're stuck at this, maybe you should consider the possibility that perhaps programming isn't what you were born to do?
[/quote]

I'm a friend of his and he was talking to me about the issue. From what I can tell, he's been having trouble understanding how to solve it as opposed to understanding the what side.

Like if you told a person "You have to read the user input and store it as a variable." They'd know what you mean, but not the specifics of how (using Console.Readline, etc)

That's the best way I can explain his issue.

Share this post


Link to post
Share on other sites
Telastyn    3777
[quote name='Bill Fountaine' timestamp='1341002633' post='4954082']
[quote name='boogyman19946' timestamp='1341002263' post='4954081']
I think Telastyn meant that instead of storing your input as a single string, you can keep the input separated and THEN to display it you can construct the string from the input.
[/quote]

I'm just not quite sure on how to do this stuff.
[/quote]

Then start smaller. Can you make a program that takes two numbers as input and prints their output?

Snob or not, that sort of program is hour 2 or 3 of learning C# from nothing. I find it hard to believe that you've done much of anything in 4 years without realizing that you're accomplishing nothing. Just say "hey, I'm a beginner". Nothing wrong with that, and we'll be able to provide better answers for your situation.

Share this post


Link to post
Share on other sites
Considering I have a million books/tutorials, with no real direction. Meh

I wish I could find something similar to this for C#

[url="http://www.cplusplus.com/forum/articles/12974/"]http://www.cplusplus...articles/12974/[/url]

Working from the ground up with pretty much everything you need to learn, with exercises/sample programs to make on your own.

Almost every tutorial/book I've come across, claims to be for beginners, but throws 20 pages of code at you for like the 2nd or 3rd concepts, when it could just be something simple. But no, they have to throw a bunch of overly complicated code in to confuse people, instead of just showing how to do that one small concept.

Maybe I should just stop asking for help. Whenever I do I get chewed out by people. Edited by Bill Fountaine

Share this post


Link to post
Share on other sites
laztrezort    1058
Building an expression parser, using Winforms, is not what I would consider a "beginner project to learn C#".

My advice: start with console applications for now, trying to learn Winforms + C# + general programming all at once is a bit much.

As Telastyn said, make a console application that takes input from the user and adds them together first.

Share this post


Link to post
Share on other sites
[quote name='laztrezort' timestamp='1341006566' post='4954109']
Building an expression parser, using Winforms, is not what I would consider a "beginner project to learn C#".

My advice: start with console applications for now, trying to learn Winforms + C# + general programming all at once is a bit much.

As Telastyn said, make a console application that takes input from the user and adds them together first.
[/quote]

That's easy to do..

Share this post


Link to post
Share on other sites
Telastyn    3777
[quote name='Bill Fountaine' timestamp='1341026215' post='4954182']
[quote name='laztrezort' timestamp='1341006566' post='4954109']
Building an expression parser, using Winforms, is not what I would consider a "beginner project to learn C#".

My advice: start with console applications for now, trying to learn Winforms + C# + general programming all at once is a bit much.

As Telastyn said, make a console application that takes input from the user and adds them together first.
[/quote]

That's easy to do..
[/quote]

Then do it. Personally, I'm a bit skeptical that you can accomplish that without needing someone to hold your hand.

Once you've done that, have the user enter the input via form rather than console.

Once you've done that, have the user input the operation as well.

Once you've done that, have the user able to input multiple inputs and operations to perform.

There's your direction. No more excuses. Edited by Telastyn

Share this post


Link to post
Share on other sites
Oberon_Command    6081
[quote]Almost every tutorial/book I've come across, claims to be for beginners, but throws 20 pages of code at you for like the 2nd or 3rd concepts, when it could just be something simple. But no, they have to throw a bunch of overly complicated code in to confuse people, instead of just showing how to do that one small concept.[/quote]

That's because much of the time, that "one small concept" cannot really be demonstrated in isolation. To demonstrate virtual functions, for instance, one would need at least three classes plus an entry-point function (possibly a third class to retain this entry-point method, if you're using C#). To demonstrate the real power thereof, one would need something much more substantial. An extreme example: to demonstrate the basic opening of a window in the Win32 API from C or C++, one would need several dozens of lines of code just to open the window, and then another few lines just to keep the window open!

Besides showing the syntax of the feature, to properly show off a concept I would argue that one needs to actually demonstrate the practical use of that feature, which means showing a non-trivial program that actually uses it to accomplish something. While I understand your "20 pages of code" to be hyperbole, I believe this also has a different purpose unrelated to merely demonstrating non-trivially the concepts being taught - consider that as you code more and more, your programs will grow larger, and it's highly unlikely that you'll ever be dealing with "one small concept" at a time - you'll be dealing with pages upon pages of code all on your screen at once. In my experience as an intern/co-op alone I've come across source code files that are literally THOUSANDS of lines of code in length! If it were me, I would be putting those "20 pages of code" there in part to get you used to looking at (and understanding) lots and lots of code at once - if you want to be a programmer, the reality is that you are going to need to be able to a) read other people's code b) read and understand LOTS of other people's code.

[quote name='Bill Fountaine' timestamp='1341029997' post='4954194']
My problem isn't knowing how to solve the solution.

The problem is not knowing the syntax to solve specific problems.
[/quote]

In that case, let's do it this way. You provide the pseudocode (or a list of steps in plain English, whichever you'd prefer) to the solution you have in mind, and someone here (possibly me) can show you the C# syntax for those specific tasks which will do what you have in mind. I personally will not give you the whole source code to the solution; knowing the solution, and having acquired the syntax you need, you should be able to put the pieces together yourself. Edited by Oberon_Command

Share this post


Link to post
Share on other sites
Xai    1838
OK, first.

1. Object Oriented programming ... break your programming down into "classes", related to logical sets of data, and the methods that manipulate that data.
2. Focus on building the LOGICAL classes, separate from your UI.

So, don't write a dozen input hanlders doing all your math ... write a dozen input handlers calling methods, which do the math ... now in a real program there is nothing wrong with event handlers the size of yours (3 lines long) ... but since this is half the logic of your program, you are not solving your problem cleanly.

There are at least 5-10 reasonable and very different ways to solve the problem you are asking (and millions of smaller varieties). Programming is about thinking through problems and we all think different (like musicians or painters) ... so all we can do is either show you how we would do it and hope you can generalize, or show you general techniques and hope you can apply them specifically.

But to help you out a bit ... first a thought, try to store your variables in a "natural" manner completely not realated to your UI. what is "natural" depends on you point of view. If you were implementing a more simple calculator "natural" might be:

a variable called something like "accumulator", "currentValue", "register" or the like ... which holds the total so far ... ie "0" when reset, and the number that is displayed after users press the "=" etc.

a variable called "operator", "pendingOperation", "state" or some such .... which holds the operation the user has requested after the press something like "+". and would be able to detect the when there isn't one (ie if the user types "3+3=" after the "=" the pending operation is null, so that you can tell if the user then types "53" then are doing the "set value to ..." operation, which doesn't care what the previous value was ... wheras if they type "+" then "53" they are doing the "add value ..." operation which does use the previous / current value.

now of course, i've only hinted at posibilities ... over about 17 years of programming, I've written calculators for examples, for fun, and for trying out new programming languages or ideas probably 7 or 8 times ... none are just like I described, but that's the point, its just a program to think up however you like ... and then work through it tell it makes since AND works.

Good luck. Edited by Xai

Share this post


Link to post
Share on other sites
I have no problem learning, it's just finding the stuff I need to learn to accomplish what I need to.

Like, getting the calculator to add multiple numbers. I'd have no problem if I found something that teaches me how to do it.

I just need to find the right learning materials for certain things, thats all.

Share this post


Link to post
Share on other sites
Oberon_Command    6081
[quote name='Bill Fountaine' timestamp='1341032033' post='4954197']
Like, getting the calculator to add multiple numbers.
[/quote]

So, my attempted summary of the situation.

You have a textbox containing a string which represents the expression to be calculated.
You want to take the equation represented in string in the textbox and compute the output of the expression.
But the string representation of the expression isn't very useful to you - at least, not yet.

Am I correct so far?

Share this post


Link to post
Share on other sites
[quote name='Oberon_Command' timestamp='1341033093' post='4954206']
[quote name='Bill Fountaine' timestamp='1341032033' post='4954197']
Like, getting the calculator to add multiple numbers.
[/quote]

So, my attempted summary of the situation.

You have a textbox containing a string which represents the expression to be calculated.
You want to take the equation represented in string in the textbox and compute the output of the expression.
But the string representation of the expression isn't very useful to you - at least, not yet.

Am I correct so far?
[/quote]

yes

I want to have the calculator able to deal with multiple numbers instead of just 2.

97 + 576 + 46, etc.

I originally thought storing each number in an array/list somehow would do the trick, but dealing with taking the numbers out of the string after each math symbol is what has me stuck atm.

Share this post


Link to post
Share on other sites
Oberon_Command    6081
[quote name='Bill Fountaine' timestamp='1341033328' post='4954207']
[quote name='Oberon_Command' timestamp='1341033093' post='4954206']
[quote name='Bill Fountaine' timestamp='1341032033' post='4954197']
Like, getting the calculator to add multiple numbers.
[/quote]

So, my attempted summary of the situation.

You have a textbox containing a string which represents the expression to be calculated.
You want to take the equation represented in string in the textbox and compute the output of the expression.
But the string representation of the expression isn't very useful to you - at least, not yet.

Am I correct so far?
[/quote]

yes

I want to have the calculator able to deal with multiple numbers instead of just 2.

97 + 576 + 46, etc.

I originally thought storing each number in an array/list somehow would do the trick, but dealing with taking the numbers out of the string after each math symbol is what has me stuck atm.
[/quote]

Okay.

Just so we're on the same page here: leaving aside the problem of "taking the numbers out of the string" (there's a specific term for this - expression parsing - which we'll get to in a moment), have you determined how to deal with the numbers once they're "out of the string?" If so, can you please post the code so that we can see where you're going with it? If not, let's tackle that problem, first since it's easier - write code that takes each number in an array (or a list, if you prefer - this is what I would prefer, for reasons that will become clear later) and adds them together.

As an aside: I often find it helpful to write a program in [i]chunks[/i] according to what I already know how to do. If I know how one particular step works, and I know exactly what sort of thing I'm going to get from the steps before it but not how that predecessor step will work, then I can write that particular step in isolation with some "dummy" test data in the format that I think that particular step will consume once the one before it is done. That's useful for unit testing, as well - if I can verify that each part of my program works on its own when given data that I [i]know[/i] should work, then I can track down bugs more easily. Edited by Oberon_Command

Share this post


Link to post
Share on other sites
What I had in mind was adding a List of ints. Then whenever the user presses a math button, store the preceding substring of numbers in the list, but right now I'm having trouble cutting the substring of numbers out of the string. Edited by Bill Fountaine

Share this post


Link to post
Share on other sites
AdrianC    602
While some people on here are being quite rude, they are right on one thing, being a programmer is not about reading a tutorial, and then knowing how to do that 1 thing. Its about being able to solve problems on your own. Anyway.

This is probably the simplest way to approach the issue, though not necessarily the best:

Your user enters a string along the lines of 10 + 20 - 5. Parse that string and store each number in one array. Also store the symbols in a separate array.

Now you have array A = {10, 20, 5} and B = {"+"," -"} (note this is just pseudocode)

Now parse the two arrays and perform the operations. Pretty basic. If you need an actual example:

[code]
while (A.length > 1)
{
if (B[0] == "+")
{
A[1] = A[0] + A[1];
remove first element of A;
remove first element of B;
}
//add other symbol options here
}
[/code]

Now A[0] will contain the solution.

Of course for things like multiplication you'll have to take into account order of operations, but I won't solve the whole thing for you.

Share this post


Link to post
Share on other sites
Oberon_Command    6081
[quote name='Bill Fountaine' timestamp='1341034327' post='4954211']
What I had in mind was adding a List of ints. Then whenever the user presses a math button, store the preceding string of numbers in the list, but right now I'm having trouble cutting the substring of numbers out of the string.
[/quote]

I realize that. You seem very insistent on this. But work with me for a bit - try writing the "adding a list of ints" bit before you write the code that cuts the numbers out of the string. In essence, expand AdrianC's example into actual, working code. Post the code here when you're done. Edited by Oberon_Command

Share this post


Link to post
Share on other sites
I think I am just going to stop while I'm ahead so I don't make myself look any more incompetent than I already have. Obviously the concept of "program, don't just look at tutorials that teaches you how to use stuff." isn't doing anything for me. If I could find something similar to http://www.cplusplus.com/forum/articles/12974/ using C#, in terms of setup (working from the ground up, making you do exercises using stuff you've learned, etc). That would be great. The tutorials I have been watching lately, which have me jumping straight into windows forms, are the ones from http://thenewboston.org/list.php?cat=15

Problem solving is easy. I just need to learn the ins and outs of the language to know what syntax I can use to solve said problems.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this