It works to add,subtract,multiply and divide with integers, but not with decimal numbers.
It is something wrong with sum1 variables, like they are in the wrong format when a decimal is asigned too them. It's because they are declated as double, BUT I don't know how to write it differently.
double sum1 = 0;
double sum2 = 0;
bool plusButtonClicked = false;
bool subButtonClicked = false;
bool multButtonClicked = false;
bool divButtonClicked = false;
public MainWindow()
{
InitializeComponent();
}
private void NumberValidationTextBox(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
}
private void one_Click(object sender, RoutedEventArgs e)
{
numEnt.Text += one.Content;
}
private void two_Click(object sender, RoutedEventArgs e)
{
numEnt.Text += two.Content;
}
private void three_Click(object sender, RoutedEventArgs e)
{
numEnt.Text += three.Content;
}
private void four_Click(object sender, RoutedEventArgs e)
{
numEnt.Text += four.Content;
}
private void five_Click(object sender, RoutedEventArgs e)
{
numEnt.Text += five.Content;
}
private void six_Click(object sender, RoutedEventArgs e)
{
numEnt.Text += six.Content;
}
private void seven_Click(object sender, RoutedEventArgs e)
{
numEnt.Text += seven.Content;
}
private void eight_Click(object sender, RoutedEventArgs e)
{
numEnt.Text += eight.Content;
}
private void nine_Click(object sender, RoutedEventArgs e)
{
numEnt.Text += nine.Content;
}
private void zero_Click(object sender, RoutedEventArgs e)
{
numEnt.Text += zero.Content;
}
private void add_Click(object sender, RoutedEventArgs e)
{
sum1 += double.Parse(numEnt.Text);
numEnt.Clear();
plusButtonClicked = true;
subButtonClicked = false;
multButtonClicked = false;
divButtonClicked = false;
}
private void sub_Click(object sender, RoutedEventArgs e)
{
sum1 += double.Parse(numEnt.Text);
numEnt.Clear();
plusButtonClicked = false;
subButtonClicked = true;
multButtonClicked = false;
divButtonClicked = false;
}
private void mult_Click(object sender, RoutedEventArgs e)
{
sum1 += double.Parse(numEnt.Text);
numEnt.Clear();
plusButtonClicked = false;
subButtonClicked = false;
multButtonClicked = true;
divButtonClicked = false;
}
private void div_Click(object sender, RoutedEventArgs e)
{
sum1 += double.Parse(numEnt.Text);
numEnt.Clear();
plusButtonClicked = false;
subButtonClicked = false;
multButtonClicked = false;
divButtonClicked = true;
}
private void deci_Click(object sender, RoutedEventArgs e)
{
string currentInput = numEnt.Text;
bool pointFound = false;
for (int i = 0; i < currentInput.Length; i++)
{
if (currentInput[i] == '.')
pointFound = true;
}
if (pointFound == false)
numEnt.Text += ".";
}
private void equal_Click(object sender, RoutedEventArgs e)
{
if (plusButtonClicked == true)
{
sum2 = sum1 + double.Parse(numEnt.Text);
result.Text = sum2.ToString();
sum1 = 0;
}
if (subButtonClicked == true)
{
sum2 = sum1 - double.Parse(numEnt.Text);
result.Text = sum2.ToString();
sum1 = 0;
}
if (multButtonClicked == true)
{
sum2 = sum1 * double.Parse(numEnt.Text);
result.Text = sum2.ToString();
sum1 = 0;
}
if (divButtonClicked == true)
{
sum2 = sum1 / double.Parse(numEnt.Text);
result.Text = sum2.ToString();
sum1 = 0;
}
}
private void clear_Click(object sender, RoutedEventArgs e)
{
numEnt.Clear();
calculations.Clear();
result.Clear();
}
}
First of all declare your sum1 variable as double. And one more thing you need a for loop to check whether a string have a decimal point. Instead you can use string.Contains method. try this code hope it will help
double sum1 =0.0 ;
private void add_Click(object sender, RoutedEventArgs e)
{
sum1 += double.Parse(numEnt.Text);
numEnt.Clear();
plusButtonClicked = true;
subButtonClicked = false;
multButtonClicked = false;
divButtonClicked = false;
}
private void sub_Click(object sender, RoutedEventArgs e)
{
sum1 -= double.Parse(numEnt.Text);
numEnt.Clear();
plusButtonClicked = false;
subButtonClicked = true;
multButtonClicked = false;
divButtonClicked = false;
}
private void mult_Click(object sender, RoutedEventArgs e)
{
sum1 *= double.Parse(numEnt.Text);
numEnt.Clear();
plusButtonClicked = false;
subButtonClicked = false;
multButtonClicked = true;
divButtonClicked = false;
}
private void div_Click(object sender, RoutedEventArgs e)
{
sum1 /= double.Parse(numEnt.Text);
numEnt.Clear();
plusButtonClicked = false;
subButtonClicked = false;
multButtonClicked = false;
divButtonClicked = true;
}
private void deci_Click(object sender, RoutedEventArgs e)
{
string currentInput = numEnt.Text;
bool pointFound = false;
//for (int i = 0; i < currentInput.Length; i++)
//{
if(currentInput.Contains("."))//if (currentInput[i] == '.')
pointFound = true;
//}
if (pointFound == false)
numEnt.Text += ".";
}
probably dot is not your decimal separator. In this case you can use
double.Parse(string, IFormatProvider)
to set the decimal separator you want.
try this
var currentCulture = System.Globalization.CultureInfo.InstalledUICulture;
var numberFormat = (System.Globalization.NumberFormatInfo) currentCultur .NumberFormat.Clone();
numberFormat .NumberDecimalSeparator = ".";
sum1 += double.Parse(numEnt.Text, numberFormat );
Related
I am playing with a basic calculator windows app and trying to make it calculate the equation when pressing the enter key. Currently, if I give it 2+2 and click my equal button it registers 4, as it should. I would like to get the same response when I hit the enter key on the keyboard. I am attempting to do this with this code:
if (e.KeyCode == Keys.Enter)
{
equal.PerformClick();
}
the result is 2+22(last number entered is duplicated)
However, if I use a letter or F-key(as in the below code) it returns the correct answer:
if (e.KeyCode == Keys.C)
{
equal.PerformClick();
}
For reference the following is the code that "equal.PerformClick()" is calling
decimal numA;
decimal numB;
decimal result = 0;
//-------------------------------------------------------------
decimal.TryParse(this.first_num_label.Text, out numA);
decimal.TryParse(this.label1.Text, out numB);
if (this.operator_name.Text == "+")
{
result = numA + numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "-")
{
result = numA - numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "x")
{
result = numA * numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "/")
{
result = numA / numB;
}
//---------------------------------------------------------------
this.label1.Text = result.ToString();
this.first_num_label.Text = "";
this.operator_name.Text = "";
here is the entire code:.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Calc_project
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void clear_Click(object sender, EventArgs e)
{
//this.label1.Text = "";
this.label1.ResetText();
}
private void one_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "1";
}
private void two_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "2";
}
private void three_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "3";
}
private void four_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "4";
}
private void five_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "5";
}
private void six_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "6";
}
private void seven_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "7";
}
private void eight_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "8";
}
private void nine_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "9";
}
private void zero_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "0";
}
private void plus_Click(object sender, EventArgs e)
{
this.operator_name.Text = "+";
if (this.label1.Text != "")
{
this.first_num_label.Text = this.label1.Text;
}
this.label1.ResetText();
}
private void minus_Click(object sender, EventArgs e)
{
this.operator_name.Text = "-";
if (this.label1.Text != "")
{
this.first_num_label.Text = this.label1.Text;
}
this.label1.ResetText();
}
private void multiply_Click(object sender, EventArgs e)
{
this.operator_name.Text = "x";
if (this.label1.Text != "")
{
this.first_num_label.Text = this.label1.Text;
}
this.label1.ResetText();
}
private void div_Click(object sender, EventArgs e)
{
this.operator_name.Text = "/";
if (this.label1.Text != "")
{
this.first_num_label.Text = this.label1.Text;
}
this.label1.ResetText();
}
private void equal_Click(object sender, EventArgs e)
{
decimal numA;
decimal numB;
decimal result = 0;
//-------------------------------------------------------------
decimal.TryParse(this.first_num_label.Text, out numA);
decimal.TryParse(this.label1.Text, out numB);
if (this.operator_name.Text == "+")
{
result = numA + numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "-")
{
result = numA - numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "x")
{
result = numA * numB;
}
//---------------------------------------------------------------
if (this.operator_name.Text == "/")
{
result = numA / numB;
}
//---------------------------------------------------------------
this.label1.Text = result.ToString();
this.first_num_label.Text = "";
this.operator_name.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
this.label1.ResetText();
this.first_num_label.ResetText();
this.operator_name.ResetText();
}
private void Decimal_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + ".";
}
private void button2_Click(object sender, EventArgs e)
{
decimal len;
decimal wit;
decimal area;
decimal.TryParse(this.textBox1.Text, out len);
decimal.TryParse(this.textBox2.Text, out wit);
area = len * wit;
if (ft.Checked == true)
{
this.label2.Text = area.ToString() +" square feet";
}
if (meters.Checked == true)
{
this.label2.Text = area.ToString() +" square meters";
}
if (cm.Checked == true)
{
this.label2.Text = area.ToString() + " square centimeters";
}
if (yards.Checked == true)
{
this.label2.Text = area.ToString() + " square yards";
}
//else
//{
// this.label2.Text = area.ToString();
//}
}
private void button3_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
this.textBox2.Text = "";
this.label2.ResetText();
}
private void button4_Click(object sender, EventArgs e)
{
decimal ar;
decimal cov;
decimal req;
//--------------------------------------------
decimal.TryParse(this.textBox4.Text, out ar);
decimal.TryParse(this.textBox3.Text, out cov);
//--------------------------------------------
req = ar / cov;
this.requirement.Text = req.ToString() + " Gallons";
}
private void button5_Click(object sender, EventArgs e)
{
decimal Slabar;
decimal Slabtk;
decimal TKft;
decimal cubFt;
decimal ConYard;
//--------------------------------------------
decimal.TryParse(this.textBox5.Text, out Slabar);
decimal.TryParse(this.textBox6.Text, out Slabtk);
//--------------------------------------------
TKft = Slabtk / 12;
cubFt = Slabar * TKft;
ConYard = cubFt / 27;
//--------------------------------------------
this.label10.Text = ConYard.ToString();
}
private void tabControl1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
equal.PerformClick();
}
if (e.KeyCode == Keys.F1) //this code works
{
MessageBox.Show("test");
}
if (e.KeyCode == Keys.Escape) //so does this
{
this.Close();
}
if (e.KeyCode == Keys.NumPad9) // also works
{
this.label1.Text = this.label1.Text + "9";
}
if (e.KeyCode == Keys.F2)
{
equal.PerformClick();
}
}
}
}
Based on my test, your code works well. If you still have problems, I suggest you can use Form_KeyDown event.
Here is a code example you can refer to.
public Form1()
{
InitializeComponent();
this.KeyPreview = true;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
equal.PerformClick();
}
}
I fixed the control focus to textbox1 to prevent the Enter key from being affected by the input number.
After each number is entered, please set textBox1.Focus(). method.
As shown below:
private void one_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "1";
textBox1.Focus();
}
private void two_Click(object sender, EventArgs e)
{
this.label1.Text = this.label1.Text + "2";
textBox1.Focus();
}
......
......
Finally, it is best for you to check if the enter key is normal.
I'm assuming you are listening on the KeyPress event? If so, have you tried casting the Keys.Enter value to a char?
private void element_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
{
// Do stuff here
}
}
Keys.Enter and Keys.Return return the same value, so it doesn't matter which one you choose.
I've created a Typing Test Form that already works:
The Richtextbox where a Random word or paragraph will be shown
The Textbox2 where you type
But How to code everytime you type a letter if the Richtextbox and Textbox2 are equal (==) the same letter you type will be highlighted to color gray on Richtextbox until you completed a word then the whole paragraph
{
private int numberOfWords = 0;
private int counter = 300;
string[] randomWords = new string[] {
"It was Richter Belmont, the legendary vampire hunter, who succeeded in finally ending the menace of Count Dracula, Lord of the Vampires who had been brought back from the grave by the dark priest Shaft.",
"Being entirely honest with oneself is a good exercise.",
"With great power comes great responsibility.",
"Whosoever holds this hammer, if he be worthy, shall possess the power of Thor.",
"Coming from your friendly neighborhood Spider-Man!.",
"The time has once again come for the forces of Good and Evil to engage in their ancient battle. Dracula's castle beckons for you. And no man can say who shall emerge victorious.",};
public Advance()
{
InitializeComponent();
}
static void HighlightPhrase(RichTextBox box, string phrase, Color color)
{
int pos = box.SelectionStart;
string s = box.Text;
for (int ix = 0; ;)
{
int jx = s.IndexOf(phrase, ix, StringComparison.CurrentCultureIgnoreCase);
if (jx < 0) break;
box.SelectionStart = jx;
box.SelectionLength = phrase.Length;
box.SelectionColor = color;
ix = jx + 1;
}
box.SelectionStart = pos;
box.SelectionLength = 0;
}
private void button1_Click(object sender, EventArgs e)
{
richTextBox1.Text = randomWords[new Random().Next(0, randomWords.Length)];
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = true;
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000; // 1 second
timer1.Start();
textBox2.Focus();
}
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if ((e.KeyCode == Keys.Enter) && (richTextBox1.Text == textBox2.Text))
{
richTextBox1.Text = randomWords[new Random().Next(0, randomWords.Length)];
textBox2.Clear();
numberOfWords += 1;
label4.Text = numberOfWords.ToString();
}
else if ((e.KeyCode == Keys.Enter) && (richTextBox1.Text != textBox2.Text))
{
string message = "Fail. Try again";
MessageBox.Show(message);
timer1.Stop();
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = false;
richTextBox1.Clear();
textBox2.Clear();
counter = 300;
numberOfWords = 0;
label1.Text = counter.ToString();
label4.Text = numberOfWords.ToString();
richTextBox1.Focus();
}
}
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
if (counter == 0)
timer1.Stop();
label1.Text = counter.ToString();
if (label1.Text == "0")
{
string message = "Corrected Paragraph ";
string title = "Result";
MessageBox.Show(message + numberOfWords.ToString(), title);
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = false;
richTextBox1.Clear();
textBox2.Clear();
counter = 240;
numberOfWords = 0;
label1.Text = counter.ToString();
label4.Text = numberOfWords.ToString();
richTextBox1.Focus();
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
var TypingTest = new TypingTest();
TypingTest.Closed += (s, args) => this.Close();
TypingTest.Show();
}
private void Advance_Load(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
timer1.Stop();
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = false;
richTextBox1.Clear();
textBox2.Clear();
counter = 300;
numberOfWords = 0;
label1.Text = counter.ToString();
label4.Text = numberOfWords.ToString();
richTextBox1.Focus();
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
textBox2.Focus();
richTextBox1.Text = randomWords[new Random().Next(0, randomWords.Length)];
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = true;
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000; // 1 second
timer1.Start();
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
HighlightPhrase(richTextBox1, "a", Color.Red);
}
}
Hi I am struggling to keep a value in my calculator's text box when I add a decimal point to a number and then want to add another number after the decimal point. Here is my code:
What code must I add to keep the value in the text box after I added a decimal point? Thank you!
public Form1()
{
InitializeComponent();
}
double total1 = 0;
double total2 = 0;
bool plusButtonClicked = false;
bool subtractButtonClicked = false;
bool multiplyButtonClicked = false;
bool divideButtonClicked = false;
private void btnSeven_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnSeven.Text;
}
private void btnNine_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnNine.Text;
}
private void btnEquals_Click(object sender, EventArgs e)
{
if (plusButtonClicked == true)
{
total2 = total1 + double.Parse(txtDisplay.Text);
}
else if (subtractButtonClicked == true)
{
total2 = total1 - double.Parse(txtDisplay.Text);
}
else if (multiplyButtonClicked == true)
{
total2 = total1 * double.Parse(txtDisplay.Text);
}
else if (divideButtonClicked == true)
{
total2 = total1 / double.Parse(txtDisplay.Text);
}
{
txtDisplay.Text = total2.ToString();
total1 = 0;
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = true;
subtractButtonClicked = false;
multiplyButtonClicked = false;
divideButtonClicked = false;
}
private void btnOne_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnOne.Text;
}
private void btnTwo_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnTwo.Text;
}
private void btnThree_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnThree.Text;
}
private void btnFour_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnFour.Text;
}
private void btnFive_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnFive.Text;
}
private void btnSix_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnSix.Text;
}
private void btnEight_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnEight.Text;
}
private void btnPoint_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnPoint.Text;
}
private void btnZero_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnZero.Text;
}
private void btnSubtract_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = false;
subtractButtonClicked = true;
multiplyButtonClicked = false;
divideButtonClicked = false;
}
private void btnMultiply_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = false;
subtractButtonClicked = false;
multiplyButtonClicked = true;
divideButtonClicked = false;
}
private void btnDivide_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = false;
subtractButtonClicked = false;
multiplyButtonClicked = false;
divideButtonClicked = true;
}
private void btnClear_Click(object sender, EventArgs e)
{
txtDisplay.Clear();
}
}
}
The issue seems to be that you are doing this:
private void some_button_Click(object sender, EventArgs e)
{
txtDisplay.Text = btnEight.Text;
}
So, if you click 4, and then . it'll show 4. , but when you click 5, it'll set it to 5.
You need to add to the previous on all your numbers ... (just like you do with the . button)
As Noctis said you need to add to the previous in all your click events. Like :
private void some_button_Click(object sender, EventArgs e)
{
txtDisplay.Text += ((Button)sender).Text;
}
the answer is simple
txtDisplay.Text += Button.Text;
Improve your code
public class Form1:Form
{
public enum CalcStatus
{
None,
Plus,
Minus,
Divide,
Multiply
};
CalcStatus status = CalcStatus.None;
bool bHasNewFlag = false;
bool bHasEquals = false;
Decimal dMemory1 = 0M;
Decimal dMemory2 = 0M;
private void CalcButton_Click(object sender, EventArgs e) // This event will be handled by Plus,Minus,Devide and Multiply
{
Decimal.TryParse(txtDisplay.Text,out dMemory1);
switch(((button)sender).Text)
{
case "+":
status = CalcStatus.Plus;
break;
case "-":
status = CalcStatus.Minus;
break;
case "/":
status = CalcStatus.Divide;
break;
case "*":
status = CalcStatus.Multiply;
break;
}
bHasNewFlag = true;
bHasEquals =false;
dMemroy2 = 0M;
}
private void NumButton_Click(object sender, EventArgs e) // This event will be handled by numbers (0-9)
{
int iNumber = 0;
int.TryParse(((button)sender).Text, out iNumber);
if (bHasNewFlag)
txtDisplay.Text = string.empty;
txtDisplay.Text += iNumber.ToString();
bHasEquals =false;
dMemroy2 = 0M;
}
private void EqualsTo_Click(object sender, EventArgs e) // This event will be handled by Equals To (=)
{
Decimal dVal = 0M;
if (bHasEquals == false)
Decimal.TryParse(txtDisplay.Text, out dMemory1);
switch(status)
{
case "+":
dVal = dMemory1 + dMemory2;
break;
case "-":
status = CalcStatus.Minus;
dVal = dMemory1 - dMemory2;
break;
case "/":
dVal = dMemory1 / dMemory2;
break;
case "*":
dVal = dMemory1 * dMemory2;
break;
}
txtDisplay.Text = dVal;
bHasEquals =true;
}
}
Do not take boolean flag for each button. because, you can do one thing at one time.
Updates:
My suggestion is when you have status like Plus, Minus, Divide, etc. then you can do any one thing at a time.
for example here you have to manage 4 variables on each button click instead of one.
so use Enumaration when you have single status value.
public enum CalcStatus
{
None,
Plus,
Minus,
Divide,
Multiply
};
CalcStatus status = CalcStatus.None;
This is my code for the calculator written in SharpDevelop. I need to know how to overwrite a number.
In my code when I'm texting the first number and after i press the add button the textbox gets cleared.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
}
double total1 = 0;
double total2 = 0;
void BtnOneClick(Object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnOne.Text;
}
void BtnTwoClick(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnTwo.Text;
}
...
void BtnZeroClick(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnZero.Text;
}
void BtnClearClick(object sender, EventArgs e)
{
txtDisplay.Clear();
}
void BtnPlusClick(object sender, EventArgs e)
{
total1 += double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = true;
minusButtonClicked = false;
multiplyButtonClicked = false;
divideButtonClicked = false;
}
...
bool plusButtonClicked = false;
bool minusButtonClicked = false;
bool multiplyButtonClicked = false;
bool divideButtonClicked = false;
}
i think you want
void BtnPlusClick(object sender, EventArgs e)
{
total1 += double.Parse(txtDisplay.Text);
txtDisplay.Text = total1.toString();
Edit: .Clear will remove the text from the text box.. I think if you wanted something else to happen then you need to rethink what you are trying to do
Edit2 if this isnt what you wanted I dont know what is
int total = 0;
bool newNum = true;
//1
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = newNum ? "1" : textBox1.Text + "1";
newNum = false;
}
//Add
private void button2_Click(object sender, EventArgs e)
{
newNum = true;
total += int.Parse(textBox1.Text);
textBox1.Clear();
}
//Equals
private void button3_Click(object sender, EventArgs e)
{
textBox1.Text = total.ToString();
}
It's beacause of this line:
txtDisplay.Clear();
in your method
BtnPlusClick();
if you want to clear it only when you start to provide next number - just chceck your bool flags(plusButtonClicked, etc.) - if on of them is set to true - then make
txtDisplay.Clear();
Hello everyone and thanks for helping me.
I made this calculator in C# and i got one problem.
When i add something like 5+5+5 it gives me correct result but when i want to substract more than two number and also divide or multiply more than two number i don't get correct result.
Do you know what i am doing wrong,
Thank you very much!
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 Calculator : Form
{
public Calculator()
{
InitializeComponent();
}
private void btnOne_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnOne.Text;
//txtDisplay.Text = btnOne.Text;
}
private void btnTwo_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnTwo.Text;
}
private void btnThree_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnThree.Text;
}
private void btnFour_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnFour.Text;
}
private void btnFive_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnFive.Text;
}
private void btnSix_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnSix.Text;
}
private void btnSeven_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnSeven.Text;
}
private void btnEight_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnEight.Text;
}
private void btnNine_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnNine.Text;
}
private void btnZero_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + btnZero.Text;
}
private void btnClear_Click(object sender, EventArgs e)
{
txtDisplay.Clear();
}
private void btnPoint_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + ",";
}
double total1 = 0;
double total2 = 0;
bool plusButtonClicked = false;
bool minusButtonClicked = false;
bool divideButtonClicked = false;
bool multiplyButtonClicked = false;
private void btnPlus_Click(object sender, EventArgs e)
{
plusButtonClicked = true;
minusButtonClicked = false;
divideButtonClicked = false;
multiplyButtonClicked = false;
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
}
private void btnMinus_Click(object sender, EventArgs e)
{
plusButtonClicked = false;
minusButtonClicked = true;
divideButtonClicked = false;
multiplyButtonClicked = false;
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
}
private void btnDivide_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = false;
minusButtonClicked = false;
divideButtonClicked = true;
multiplyButtonClicked = false;
}
private void btnMultiply_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = false;
minusButtonClicked = false;
divideButtonClicked = false;
multiplyButtonClicked = true;
}
private void btnEquals_Click(object sender, EventArgs e)
{
if (plusButtonClicked == true)
{
total2 = total1 + double.Parse(txtDisplay.Text);
}
else if (minusButtonClicked == true)
{
total2 = total1 - double.Parse(txtDisplay.Text);
}
else if (divideButtonClicked == true)
{
total2 = total1 / double.Parse(txtDisplay.Text);
}
else if (multiplyButtonClicked == true)
{
total2 = total1 * double.Parse(txtDisplay.Text);
}
txtDisplay.Text = total2.ToString();
total1 = 0;
}
}
}
This code is has not been thoroughly tested. Why don't you try something like the following:
using System;
using System.Windows.Forms;
namespace Calculator
{
public enum Operator
{
None,
Add,
Minus,
Divide,
Multiply
}
public partial class Calculator : Form
{
private double total = 0;
private double currentValue = 0;
private Operator currentOperator;
public Calculator()
{
InitializeComponent();
}
private void btnOne_Click(object sender, EventArgs e)
{
ShowInput(btnOne.Text);
}
private void btnTwo_Click(object sender, EventArgs e)
{
ShowInput(btnTwo.Text);
}
private void btnThree_Click(object sender, EventArgs e)
{
ShowInput(btnThree.Text);
}
private void btnFour_Click(object sender, EventArgs e)
{
ShowInput(btnFour.Text);
}
private void btnFive_Click(object sender, EventArgs e)
{
ShowInput(btnFive.Text);
}
private void btnSix_Click(object sender, EventArgs e)
{
ShowInput(btnSix.Text);
}
private void btnSeven_Click(object sender, EventArgs e)
{
ShowInput(btnSeven.Text);
}
private void btnEight_Click(object sender, EventArgs e)
{
ShowInput(btnEight.Text);
}
private void btnNine_Click(object sender, EventArgs e)
{
ShowInput(btnNine.Text);
}
private void btnZero_Click(object sender, EventArgs e)
{
ShowInput(btnZero.Text);
}
private void btnClear_Click(object sender, EventArgs e)
{
currentOperator = Operator.None;
txtDisplay.Clear();
total = 0;
}
private void btnPoint_Click(object sender, EventArgs e)
{
txtDisplay.Text = txtDisplay.Text + '.';
}
private void btnPlus_Click(object sender, EventArgs e)
{
ApplyOperator(Operator.Add);
}
private void btnMinus_Click(object sender, EventArgs e)
{
ApplyOperator(Operator.Minus);
}
private void btnDivide_Click(object sender, EventArgs e)
{
ApplyOperator(Operator.Divide);
}
private void btnMultiply_Click(object sender, EventArgs e)
{
ApplyOperator(Operator.Multiply);
}
private void btnEquals_Click(object sender, EventArgs e)
{
Evaluate();
txtDisplay.Text = Convert.ToString(total);
}
private void Evaluate()
{
switch (currentOperator)
{
case Operator.Add:
total += currentValue;
break;
case Operator.Minus:
total -= currentValue;
break;
case Operator.Divide:
total /= currentValue;
break;
case Operator.Multiply:
total *= currentValue;
break;
case Operator.None:
break;
}
currentValue = 0;
currentOperator = Operator.None;
}
private void ApplyOperator(Operator op)
{
if (currentOperator != Operator.None)
{
Evaluate();
}
else
{
total = double.Parse(txtDisplay.Text);
}
txtDisplay.Clear();
currentOperator = op;
}
private void ShowInput(String n)
{
txtDisplay.Text = txtDisplay.Text + n;
currentValue = double.Parse(txtDisplay.Text);
}
}
}
I would still recommend that you would end up making some form of operator parser. Take a look here or look in to the 'Shunting Yard' algorithm yourself.
Think about it. What the minus_clicked code is doing is adding all of the operands EXCEPT the last one together, and then the equals_clicked code is doing the arithmetic on the result of minus_clicked, and the value of the textbox (which is the last operand, I assume). So, since the operation you're doing in minus_clicked is addition, what you're getting for x - y - z is really:
(X + Y) - Z
I would consider refactoring a little bit, but if you wanted to keep the code the way it is, I'd probably just change the minus_clicked code to subtract rather than add.
Also, #rhysw is right. If you wan't this to be fully functional, you're gonna have to add priority logic to it as well.
in your code:
private void btnMultiply_Click(object sender, EventArgs e)
{
total1 = total1 + double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = false;
minusButtonClicked = false;
divideButtonClicked = false;
multiplyButtonClicked = true;
}
you aren't applying the correct operator, you have total1 = total1 + ... Change the operator to *.
The logic for calculating the product, quotient, and difference in your code is total1 = total1 + double.Parse(txtDisplay.Text); which is why the addition works, but nothing else. So change the logic so it either divides, multiplies, or subtracts, instead of adding.
I looked at the code, and it looks like in each button you're just adding each time. So any time to click a button you're just going to keep adding. Just change the opps to their appropriate button. like so:
private void btnMinus_Click(object sender, EventArgs e)
{
plusButtonClicked = false;
minusButtonClicked = true;
divideButtonClicked = false;
multiplyButtonClicked = false;
total1 = total1 - double.Parse(txtDisplay.Text);
txtDisplay.Clear();
}
private void btnDivide_Click(object sender, EventArgs e)
{
total1 = total1 / double.Parse(txtDisplay.Text);
txtDisplay.Clear();
plusButtonClicked = false;
minusButtonClicked = false;
divideButtonClicked = true;
multiplyButtonClicked = false;
}