Problems in windows application with error handling and textbox display - c#

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!

Related

Simple Calculator (C#) - How do I get result of calculation involving two integers in textBox2?

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.

desired output not coming

double num1, num2, result;
String sign = "";
protected void add_Click(object sender, EventArgs e)
{
sign = "+";
num1 = double.Parse(tb1.Text);
tb1.Text = "";
}
protected void equal_Click(object sender, EventArgs e)
{
try
{
num2 = double.Parse(Convert.ToString(tb1.Text));
if(sign.Equals("+")){
result = num1 + num2;
tb1.Text = Convert.ToString(result);
}
if(sign.Equals("-")){
result = num1 - num2;
tb1.Text = Convert.ToString(result);
}
if(sign.Equals("*")){
result = num1 * num2;
tb1.Text = Convert.ToString(result);
}
if(sign.Equals("/")){
result = num1 / num2;
tb1.Text = Convert.ToString(result);
}
}
catch (Exception ex)
{
tb1.Text = ex.Message;
}
}
protected void minus_Click(object sender, EventArgs e)
{
sign = "-";
num1 = double.Parse(tb1.Text);
tb1.Text = "";
}
protected void divide_Click(object sender, EventArgs e)
{
sign = "/";
num1 = double.Parse(tb1.Text);
tb1.Text = "";
}
protected void product_Click(object sender, EventArgs e)
{
sign = "*";
num1 = double.Parse(tb1.Text);
tb1.Text = "";
}
this is my simple program which performs arithmetic operations, but when i click '=' button it does not gives me result instead it gives me the last number entered in the textfield..
anyone knows whats the problem with code?
Web applications are stateless, a new instance of your class is created for each request (GET or POST).
Therefore the fields in the class are reinitialized on every POST:
double num1, num2, result;
String sign = "";
You need to persist the values of these fields somewhere: ViewState would be one option.
A typical ViewState-backed property implementation would look something like:
public double Num1
{
get
{
o = ViewState["Num1"];
return (o == null) 0D : (double) o;
}
set
{
ViewState["Num1"] = value;
}
}
If you replace each of your fields num1, num2, result, sign with properties implemented like this (each with a unique name of course), and ViewState is enabled, then you should get the result you want.
The sign variable is being reset to an empty string on post back by this line:
String sign = "";
You need to store the value of sign in cache so that it survives between post backs.
I recommend Session to do that, like this:
protected void minus_Click(object sender, EventArgs e)
{
sign = "-";
// Store sign in Session
Session["theSign"] = sign;
num1 = double.Parse(tb1.Text);
tb1.Text = "";
}
Note: Do this same Session storing logic in the other event handlers for divide and product.
Now in Page_Load you need to check the Session for the sign value every time, like this:
protected void Page_Load(object sender, EventArgs e)
{
// Default sign value that may be changed by value in session cache
String sign = "";
// Is there a session value for theSign
if(Session["theSign"] != null)
{
// Yes, so set the sign variable value to use in click event handlers
sign = Session["theSign"].ToString();
}
}

can perform some operations but not all on c# calculator?

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();
}
}

use parentheses in c# calculator

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();

Input string was not in a correct format and how to learn c#

I am new to c# , i have read few basic concepts and now want to learn actual programming , thats why i started out with simple Calculator program
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
double num1 = 0;
double num2 = 0;
private void one_Click(object sender, EventArgs e)
{
textBox1.Text =textBox1.Text+one.Text;
}
private void clear_Click(object sender, EventArgs e)
{
textBox1.Clear();
// textBox1.Text = " ";
}
private void two_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text+two.Text;
}
private void three_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text+three.Text;
}
private void four_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text+four.Text;
}
private void five_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + five.Text;
}
private void six_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + six.Text;
}
private void seven_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + seven.Text;
}
private void eight_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + eight.Text;
}
private void nine_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + nine.Text;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void add_Click(object sender, EventArgs e)
{
num1 = num1 + double.Parse(textBox1.Text) ;
textBox1.Clear();
}
private void ten_Click(object sender, EventArgs e)
{
textBox1.Text = textBox1.Text + ten.Text;
}
private void equal_Click(object sender, EventArgs e)
{
num2 = num1 + double.Parse(textBox1.Text) ;
textBox1.Text = num2.ToString();
num1 = 0;
}
}
}
This code is given in the book and they said its working .Actual problem is it works ONLY some times and some times it gives error as " Input string was not in a correct format "
What is the solution .
My second question is -- is this right approach to learn any programming language ? or should i just continue reading some more stuff n programs ?
If some one can help me with websites containing sample programs it will be very helpful .
Your problem is parsing the double. The Parse function cannot parse a string that does not represent a double.
Consider the string "135.42", this could easily be parsed to the double value 135.42. But what if the string was "Abc#%%#". This does not represent a double value and that is where you are getting your exception.
If this is your first programming language, you should read a introductory book to C# as a new programmer.
If double.Parse can't parse the string into a double then an exception is thrown. However, it's often better to use double.TryParse as it will simply return false instead of throwing an exception.
double tmp;
if(double.TryParse(textBox1.Text, out tmp))
{
num2 = num1 + tmp;
textBox1.Text = num2.ToString();
num1 = 0;
}
else
{
//double could not be parsed from textbox
}
You need to restrict the user to input only numbers in your textbox. You can do it by using keydown event of textbox. Where you will check if inputed char was numeric, only then keep it in the textbox. Here is the solution of your problem. Have a look at this:
How do I make a textbox that only accepts numbers?
For learning C#, i would prefer:
C# 5.0 in a Nutshell: The Definitive Reference
Before you do double.Parse() you should verify the user input, i.e. That it is an actual number.
I would suggest using TryParse method instead, as such:
double num;
bool isNum = double.TryParse(Str, out num);
if (isNum)
{
//Calculate here
}
If you wanted to handle invalid arguments more gracefully you could use Double.TryParse instead.
Here is the magic: double.Parse(textBox1.Text)
This function accepts only numbers (with comma or dot depends on your culture) in the string. If you pass anything else you will receive the given exception. Validate the input before you parse it or Use TryParse
double valueinDouble;
var success = double.TryParse(textBox1.Text), out valueinDouble)
if (success)
{
// do the calculation here
}
The TryParse has another implementation where you can specify the culture.
var success = double.TryParse(textBox1.Text), NumberStyles.Any, new CultureInfo("en-US"), out valueinDouble)

Categories

Resources