I have implemented a calculator in C# everything apart from this is working fine, basically if I try to enter a number before a decimal point the number is reset and only then lets me enter numbers after the decimal point I'm assuming this is something stupid and will be a quick fix but I'm having no luck
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.Threading.Tasks;
using System.Windows.Forms;
namespace GrantCalculator
{
public partial class Form1 : Form
{
int count = 0;
float result = 0;
string operation = "";
bool operationPressed = false;
public Form1()
{
InitializeComponent();
}
private void btnClear_Click(object sender, EventArgs e)
{
//clearing result
txtResult.Text = "0";
result = 0;
}
private void btn_Click(object sender, EventArgs e)
{
if (count == 0)
{
//remove extra 0
if ((txtResult.Text == "0") || (operationPressed))
{
txtResult.Clear();
}
}
else if(count==1)
{
txtResult.Clear();
}
//event handler set for all number buttons which goto result textbox
operationPressed = false;
Button b = (Button)sender;
txtResult.Text += b.Text;
count = 0;
}
private void operator_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
operation = b.Text;
result = float.Parse(txtResult.Text);
operationPressed = true;
// count = 0;
}
private void btnEquals_Click(object sender, EventArgs e)
{
if (float.Parse(txtResult.Text) == 0 && operation == "/")
{
MessageBox.Show("You can't divide by 0");
}
//The math
switch (operation)
{
case "+":
txtResult.Text = (result + float.Parse(txtResult.Text)).ToString();
break;
case "-":
txtResult.Text = (result - float.Parse(txtResult.Text)).ToString();
break;
case "*":
txtResult.Text = (result * float.Parse(txtResult.Text)).ToString();
break;
case "/":
txtResult.Text = (result / float.Parse(txtResult.Text)).ToString();
break;
case "%":
txtResult.Text = (result % float.Parse(txtResult.Text)).ToString();
break;
default:
txtResult.Text = "Invalid";
break;
}
count++;
}
private void txtResult_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (!Char.IsDigit(ch) && ch != 8 && ch != '.')
{
e.Handled = true;
}
// to allow only one decimal
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
}
private void btnPoint_Click(object sender, EventArgs e)
{
Button b = new Button();
string dot = txtResult.Text;
if (dot.Contains("."))
{
txtResult.Text = txtResult.Text + b.Text;
}
else
{
txtResult.Text = txtResult.Text = ".";
}
}
}
}
Thanks in advance :)
The line at the end:
txtResult.Text = txtResult.Text = ".";
The second = should be a +.
a = b = c = d = 5; notation is valid, and will set everything to 5.
As an addition to NibblyPig's answer:
Why are you creating a new Button and why are you adding the .Text of that button (which is string.Empty since it hasn't been set) to txtResult.Text when it already contains a dot?
Optimized version would be:
private void btnPoint_Click(object sender, EventArgs e)
{
if (!txtResult.Text.Contains("."))
{
txtResult.Text += ".";
}
}
I'm still fairly new to C# programming language. I have to create a simple calculator which can add, subtract, multiply, divide two numbers of users choice without decimals. My Calculator has two input text boxes and one output text box. I've only got 4 operator buttons which are; +,-,*,/. In addition, I also added a 'Backspace' button.
When user inputs the two values, they have to press one of the operator buttons. For example; if the user types in 10 in 'textBox1' and 20 in 'textBox2' and presses 'Button15', the value of the sum will be displayed in 'textBox2'.
There is link of image below the code.
So my problem is with the code under "=" Button15 - I am able to display my user input values but there is problem with my result. I have used my own approach and it might be incorrect.
I would appreciate any help.
Here's the source code:
public partial class Form1 : Form
{
int FirstNumber;
string Operation;
string l;
public Form1()
{
InitializeComponent();
}
private void button4_Click(object sender, EventArgs e)
{
if(textBox1.Text=="0")
{
textBox1.Text = "6";
}
else
{
textBox1.Text = textBox1.Text + "6";
}
}
private void button15_Click(object sender, EventArgs e)
{
int SecondNumber;
int Result;
if (Operation == "+")
{
string l = textBox1.Text;
int index = l.IndexOf("+");
string result = l.Substring(index + 1);
SecondNumber = Convert.ToInt16(result);
Result = (FirstNumber + SecondNumber);
textBox2.Text = Convert.ToString(Result);
}
else if (Operation == "-")
{
string l = textBox1.Text;
int index = l.IndexOf("-");
string result = l.Substring(index + 1);
SecondNumber = Convert.ToInt16(result);
Result = (FirstNumber - SecondNumber);
textBox2.Text = Result.ToString();
}
else if (Operation == "x")
{
string l = textBox1.Text;
int index = l.IndexOf("x");
string result = l.Substring(index + 1);
SecondNumber = Convert.ToInt16(result);
Result = (FirstNumber * SecondNumber);
textBox2.Text = Convert.ToString(Result);
}
else if(Operation=="/")
{
string l = textBox1.Text;
int index = l.IndexOf("/");
string result = l.Substring(index + 1);
SecondNumber = Convert.ToInt16(result);
if ( SecondNumber == 0)
{
textBox1.Text = "Cannot divide by 0";
}
else
{
Result = (FirstNumber / SecondNumber);
textBox2.Text = Convert.ToString(Result);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
textBox1.Text = "1";
}
else
{
textBox1.Text = textBox1.Text + "1";
}
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
textBox1.Text = "2";
}
else
{
textBox1.Text = textBox1.Text + "2";
}
}
private void button3_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
textBox1.Text = "3";
}
else
{
textBox1.Text = textBox1.Text + "3";
}
}
private void button5_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
textBox1.Text = "5";
}
else
{
textBox1.Text = textBox1.Text + "5";
}
}
private void button6_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
textBox1.Text = "4";
}
else
{
textBox1.Text = textBox1.Text + "4";
}
}
private void button9_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
textBox1.Text = "7";
}
else
{
textBox1.Text = textBox1.Text + "7";
}
}
private void button8_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
textBox1.Text = "8";
}
else
{
textBox1.Text = textBox1.Text + "8";
}
}
private void button7_Click(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
textBox1.Text = "9";
}
else
{
textBox1.Text = textBox1.Text + "9";
}
}
private void button10_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + "0";
}
private void button11_Click(object sender, EventArgs e)
{
int FirstNumber = Convert.ToInt32(textBox1.Text);
string Operation = "-";
textBox1.Text = textBox1.Text + Operation;
}
private void button12_Click(object sender, EventArgs e)
{
int FirstNumber = Convert.ToInt32(textBox1.Text);
string Operation = "+";
textBox1.Text = textBox1.Text + Operation;
}
private void button13_Click(object sender, EventArgs e)
{
int FirstNumber = Convert.ToInt32(textBox1.Text);
string Operation = "x";
textBox1.Text = textBox1.Text + Operation;
}
private void button14_Click(object sender, EventArgs e)
{
int FirstNumber = Convert.ToInt32(textBox1.Text);
string Operation = "/";
textBox1.Text = textBox1.Text + Operation;
}
private void Form1_Load(object sender, EventArgs e)
{
int FirstNumber = Convert.ToInt32(textBox1.Text);
textBox1.Text = textBox1.Text + "0";
}
private void button16_Click(object sender, EventArgs e)
{
textBox1.Text = "0";
}
Here is the image of my calculator. The textBox1, the one at the top is happily displaying the user input but the one below, textBox2 is not working when clicked on "="
In your button event handlers you declare new FirstNumber and Operation variables and assign them. These aren't the same as the Form's FirstNumber and Operation. You don't need to declare them again, you can just assign to them.
private void button11_Click(object sender, EventArgs e)
{
int FirstNumber = Convert.ToInt32(textBox1.Text);
string Operation = "-";
textBox1.Text = textBox1.Text + Operation;
}
should be
private void button11_Click(object sender, EventArgs e)
{
FirstNumber = Convert.ToInt32(textBox1.Text);
Operation = "-";
textBox1.Text = textBox1.Text + Operation;
}
and similar for the rest of your button clicked event handlers.
First of all, please give dhe controls and event handlers meaningful names. You can change the name in the properties columns in Design View.
Secondly, you declare new variables in the methods for handling operator button clicks.
For example, you have int FirstNumber and string Operation in the event handlers. After the declaration the class variables with the same name are shadowed, and you access only the new variables inside those handlers.
Remove the int and string. The way you have it, you never change the class fields.
I wrote out a very simple code. I am trying to get it to do two things for me
I want it to continually show the user inputs and what the output would be. Right now it does not. I think this is a problem with my appendtext
should I use a try and catch for error handling? That's if the user enters more than one decimal my code crashes. I would like to know how to make it where it reverts back to one decimal and continues on.
Here is a snippet of my code.
Also to note, only in my addition method did I start the appendtext, since it didn't work and I kept getting stuck I stopped and came here...
private void button10_Click(object sender, EventArgs e) {
textBox1.AppendText(".");
}
private void button3_Click(object sender, EventArgs e) {
c = "+";
num1 = double.Parse(textBox1.Text);
textBox1.AppendText("+");
}
private void button12_Click(object sender, EventArgs e) {
c = "-";
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
}
private void button13_Click(object sender, EventArgs e) {
c = "*";
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
}
private void button14_Click(object sender, EventArgs e) {
c = "/";
num1 = double.Parse(textBox1.Text);
textBox1.Text = "";
}
private void button4_Click(object sender, EventArgs e) {
num2 = double.Parse(textBox1.Text);
double result;
if (c == "+") {
result = num1 + num2;
textBox1.Text = result.ToString();
}
When you append "+", the num2 is equal to value1+"+"+value2 or something so try to use this code
private void button4_Click(object sender, EventArgs e) {
double result;
if (c == "+") {
num2 = double.Parse(textBox1.Text.Split('+')[1]);//bad idea but will work
result = num1 + num2;
textBox1.Text = result.ToString();
}
}
also try
private void button4_Click(object sender, EventArgs e) {
double result;
if (c == "+") {
num2 = double.Parse(textBox1.Text.SubString(textBox1.Text.LastIndexOf('+')+1));
result = num1 + num2;
textBox1.Text = result.ToString();
}
}
PS: try catch needed!
So far, my addition and subtraction work. But, my multiplication and division do not. This is because the first two numbers I put in get added and them the operation is done. Such as, if 9 * 9 + 3 should be 84, it is 21 on my calculator. That is because it is taking 9+9 + 3; as it only sees the last operator.
I have absolutely no idea how to fix this. Is there any helpful insight?
public partial class Form1 : Form
{
double num2;
double num1;
string c;
public Form1()
{
InitializeComponent();
}
private void btn0_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn0.Text;
}
private void btn1_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn1.Text;
}
private void btn2_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn2.Text;
}
private void btn3_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn3.Text;
}
private void btn4_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn4.Text;
}
private void btn5_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn5.Text;
}
private void btn6_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn6.Text;
}
private void btn7_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn7.Text;
}
private void btn8_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn8.Text;
}
private void btn9_Click(object sender, EventArgs e)
{
txtBox.Text = txtBox.Text + btn9.Text;
}
private void btnDecimal_Click(object sender, EventArgs e)
{
if (!txtBox.Text.Contains('.'))
txtBox.Text += '.';
}
private void btnClear_Click(object sender, EventArgs e)
{
txtBox.Clear();
}
private void btnAddition_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(txtBox.Text);
c = "+";
txtBox.Clear();
}
private void btnSubtraction_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(txtBox.Text);
c = "-";
txtBox.Clear();
}
private void btnMultiplication_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(txtBox.Text);
c = "*";
txtBox.Clear();
}
private void btnDivision_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(txtBox.Text);
c = "/";
txtBox.Clear();
}
private void btnEquals_Click(object sender, EventArgs e)
{
double result;
num2 = double.Parse(txtBox.Text);
switch (c)
{
case "+":
result = num1 + num2;
txtBox.Text = result.ToString();
num1 = 0;
break;
case "-":
result = num1 - num2;
txtBox.Text = result.ToString();
num1 = 0;
break;
case "*":
result = num1 * num2;
txtBox.Text = result.ToString();
num1 = 0;
break;
case "/":
if (num2 != 0)
{
result = num1 / num2;
txtBox.Text = result.ToString();
}
else
{
txtBox.Text = "You can't divide by zero... sign up for Math 100 please =)";
}
break;
default:
result = 0;
break;
}
}
}
}
You need to do the previous operation before overwriting it with a new one:
private void btnAddition_Click(object sender, EventArgs e)
{
num2 = double.Parse(txtBox.Text);
num1 = calc(num1, num2, c);
c = "+";
txtBox.Clear();
}
where calc does the operation that you do on "=" now.
Two issues:
Look at your num1 variable every time after you click an operator other than equal. Say I start with 6*4-3. I press 6, then *. At this point num1 now becomes 6. Press 4 and - next. Now 4 is Added to Num1 making 10. Then 3 and equal is pressed, which probably gave you 7.
Second issue:
c is being overridden every time you press a different operator such as + or minus.
Solutions:
1) You could make an infix parser or
2) Modify your code to something as follow (giving example for subtraction)
private void btnSubtraction_Click(object sender, EventArgs e)
{
Equals()
c = "-";
txtBox.Clear();
}
private void btnEquals_Click(object sender, EventArgs e)
{
Equals();
txtBox.Text = Result.ToString();
result = 0;
}
private void Equals()
{
if (!double.TryParse(txtBox.Text, out num2)) return;
switch (c)
{
case "+":
result = result + num2;
break;
case "-":
result = result - num2;
break;
case "*":
result = result * num2;
break;
case "/":
result = result / num2;
break;
default:
result = num2;
break;
}
}
I think your problem is num1. Everytime you do an opperation you are just adding num1 with the value of the text box.
So I think when you press the buttons: 6*4-3= you should get 21, but you are acrually getting 7
This is because num1 is being added when you press * and - buttons, so you end up doing 6+4-3 = 7.
You need to change btnMultiplication_Click to something like:
private void btnMultiplication_Click(object sender, EventArgs e)
{
num1 = num1 * double.Parse(txtBox.Text);
c = "*";
txtBox.Clear();
}
and something similar for divide and subtract. I think subtract only works in your example because it's the last thing you do and the equals button handles it correctly.
I haven't tested this out but I think that's your problem
The mistake is that you're doing, for every operator:
num1 = num1 + double.Parse(txtBox.Text);
and that's wrong, because you're only adding every number you write in your calculator, except the last one, which is calculated correctly, due to btnEquals_Click.
In fact you check what operator you're using only when "=" is pressed, you have to do that for every operator you choose.
When any operation (+, -, /, *, =) is performed, the existing state (including the last operation) should be evaluated and replaces your first number, operation and second number.
Look at your criteria, here's the state before/after each action:
2+2+2= 6
2+
before: firstNumber=0 (default), operation="+" (default, hidden), secondNumber=2
after: firstNumber=2 (calc 0+2), operation="+", secondNumber=empty (awaiting input)
2+2+
before: firstNumber=2, operation="+", secondNumber=2
after: firstNumber=4(calc 2+2), operation="+", secondNumber=empty (awaiting input)
2+2+2=
before: 4 + 2
after: 6 + (empty)
2+3-1= 4
2+
before: 0(default) +(default) 2
after: 2 + (empty)
2+3-
before: 2 + 3
after: 5 - (empty)
2+3-1=
before: 5 - 1
after: 4 +(inferred) (empty)
6*4-3= 21
6*
before: 0(default) +(default) 6
after: 6 * (empty)
6*4-
before: 6 * 4
after: 24 - (empty)
6*4-3=
before: 24 - 3
after: 21 +(inferred) (empty)
Does that make more sense?
Also to follow standard calculator conventions you might want to consider allowing people to change the operation if the 2nd number is currently empty, e.g.
given this sequence:
6*4=-3= - perform 6*4 and see result ("="), then subtract 3 from that and show that result ("=")
6*
before: 0(default) +(default) 6 -> 6 * (empty)
6*4=: 6 * 4
after: 24 +(inferred) (empty)
6*4=-
before: 24 + (empty)
after special case: 24 - (empty)
6*4=-3=
before: 24 - 3
after: 21 +(inferred) (empty)
UPDATE:
To put this in terms of your code, you would need to change the +, -, /, * and = buttons to all work the same way. That is, take num1, c and the current value of double.Parse(txtBox.Text), perform that operation then update based on the new operation.
// is the current txtBox value new, so will be cleared and allow op change
private bool isNew = true;
// change this to default to +
string c = "+";
double num1 = 0;
private void Evaluate(string newOperand)
{
if (isNew)
{
// just update the operand, don't perform an evaluate
c = newOperand;
return;
}
double num2 = double.Parse(txtBox.Text);
switch (c)
{
case "+":
num1 = num1 + num2;
break;
// etc for -, /, *
// for "="
default:
num1 = num1 + num2;
break;
}
isNew = true;
c = newOperand;
}
// this can be assigned as the handler for buttons 0 - 9
public void btnNumber_Click(object sender, EventArgs e)
{
var button = sender as Button;
txtBox.Text += button.Text;
isNew = false;
}
// this can be assigned as the event handler for all operations: +, -, /, *, =
public void btnOperation_Click(object sender, EventArgs e)
{
var button = sender as Button;
Evaluate(button.Text);
}
I have changed the whole purpose of num1 from the way you did it, so it is now the firstNumber as in my examples above.
You might want to add a clear all that will reset num1 to 0 and c to +. You could also do this in your existing btnClear_Click by detecting a 2nd press, like many calculators do:
public void btnClear_Click(object sender, EventArgs e)
{
if (isNew)
{
num1 = 0;
c = "";
// text box should already be empty
}
else
{
isNew = true;
txtBox.Clear();
}
}
Hello I just write a simple calculator in C# and I want to improve my program to handle parentheses.
Here is my button to add 1(digit):
private void btnOne_Click(object sender, EventArgs e)
{
txtResult.Text += '1';
}
This is a method for my Plus button:
private void btnPlus_Click(object sender, EventArgs e)
{
lblChar.Text = "+";
num1 = float.Parse(txtResult.Text);
txtResult.Text = "";
}
And this is for to calculate final result:
private void btnEqual_Click(object sender, EventArgs e)
{
num2 = float.Parse(txtResult.Text);
if (lblChar.Text == "+")
{
num3 = num1 + num2;
txtResult.Text = Convert.ToString(num3);
}
}
Anyone can help me to write parentheses for my program?
You can use NCalc - Mathematical Expressions Evaluator for .NET
Expression e = new Expression("2 + (3 + 5)*6");
var result = e.Evaluate();