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();
}
}
Related
Im trying to write a program in C# that allows the user to input the number of seats sold, then the program multiples each number by the price to get how many were bough in each section. Ive gotten to the end but he program is not working because of the red line under the texbox.toString part. Can someone help me know what my errors are?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label7_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
textBox4.Text = "";
textBox3.Text = "";
textBox2.Text = "";
total.Text = "";
input1.Text = "";
input2.Text = "";
input3.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
int input1;
int input2;
int input3;
input1 = int.Parse(input1.ToString());
input2 = int.Parse(input2.ToString());
input3 = int.Parse(input3.ToString());
int sum1 = input1 * 15;
int sum2 = input2 * 12;
int sum3 = input3 * 9;
sum1 = textBox3.ToString();
sum2 = textBox2.ToString();
sum3 = textBox4.ToString();
}
}
to obtain the string written in your textBox:
textBox.Text;
to display a value sum in textBox:
textBox.Text = sum.ToString();
This is how button1_Click would look like at least:
private void button1_Click(object sender, EventArgs e)
{
int in1; // change int names to not confuse woth textboxes
int in2;
int in3;
in1 = int.Parse(input1.Text); // input1 is textBox
in2 = int.Parse(input2.Text);
in3 = int.Parse(input3.Text);
int sum1 = in1 * 15;
int sum2 = in2 * 12;
int sum3 = in3 * 9;
textBox3.Text = sum1.ToString();
textBox2.Text = sum2.ToString();
textBox4.Text = sum3.ToString();
}
You can use just
int.Parse(textbox.Text);
Use the "Text" property of the text box control instead. It would be better to have it as something like "input1.Text.Trim()", as this would remove any leading/trailing spaces that accidentally got into the input.
As a best practice, particularly while getting values from text controls in UI, it is good to use Int32.TryParse. (Please see: Parse v. TryParse)
As an additional point, your code does not follow basic naming conventions.
sum is an integer but textBox.ToString() is a string. You can't assign a string into an integer
it should be
textBox3.Text = sum1.ToString();
The problem is occurring because you are attempting to store the value of a string into an int.
The line:
sum = textBox.ToString();
is just converting the value of textBox to a string, not the value of the text in textBox, and passing it into the sum variable. That won't work.
Try this instead:
sum = Convert.ToInt32(textBox.Text);
However, if you ever want to show the value of sum in textBox, you can implicitly convert from an int to a string:
textBox.Text = sum;
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();
i have a form with 2 labels initializing random numbers and a text box to check if the answer is correct after adding the two random numbers. The problem i am having is SUBMIT processes the next set of random numbers and so the result is always incorrect. here is the code i have so far.
namespace _2ndGradeMath
{
public partial class Default : System.Web.UI.Page
{
Random random = new Random();
protected void Page_Load(object sender, EventArgs e)
{
lblNum1.Text = random.Next(0, 10).ToString();
lblNum3.Text = random.Next(0, 10).ToString();
int num1 = int.Parse(lblNum1.Text);
int num2 = int.Parse(lblNum3.Text);
lblAnswer.Text = (num1 + num2).ToString();
lblAnswer.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (TextBox1.Text != lblAnswer.Text)
{
Button1.Attributes.Add("onClick", "javascript:alert('Incorrect');");
}
else if (TextBox1.Text == lblAnswer.Text)
{
Button1.Attributes.Add("onClick", "javascript:alert('Correct');");
}
TextBox1.Text = "";
}
}
}
Use IsPostBack to only run the initializing code when the page is initially loaded:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblNum1.Text = random.Next(0, 10).ToString();
lblNum3.Text = random.Next(0, 10).ToString();
int num1 = int.Parse(lblNum1.Text);
int num2 = int.Parse(lblNum3.Text);
lblAnswer.Text = (num1 + num2).ToString();
lblAnswer.Visible = false;
}
}
Here's the problem. You are loading new random numbers each time the page loads. That's what the Page_Load function does: it runs each time the page loads which includes every time the page is submitted. So when a user presses submit new random numbers are assigned, which makes his answer wrong. You need to assign random numbers in only two instances:
First, when the page loads for the first time. Which can be done by checking the property IsPostBackis false.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack){
lblNum1.Text = random.Next(0, 10).ToString();
lblNum3.Text = random.Next(0, 10).ToString();
}
.
.
.
}
Second, when the user answers correctly.
else if (TextBox1.Text == lblAnswer.Text)
{
Button1.Attributes.Add("onClick", "javascript:alert('Correct');");
lblNum1.Text = random.Next(0, 10).ToString();
lblNum3.Text = random.Next(0, 10).ToString();
}
Consider adding this code to PreRender:
protected override void OnPreRender(EventArgs e)
{
Session["Answer"] = lblAnswer.Text;
base.OnPreRender(e);
}
and then in the Click grab the answer from Session like this:
if (TextBox1.Text != Session["Answer"])
and bear in mind I'm assuming that you actually want to generate new numbers on every post back with this answer.