C# Calculator with memory buttons - c#

I am having some difficulties making my calculator have the ability to store values. The calculator works for everything except this and I am quite stuck. I think I might have to declare some constants or something that I am missing right now. I am super new at this and appreciate the help. Here is my code. Thanks for any help guys. Right now I am getting no errors but nothing works either! I am also supposed to make it so a "M" appears in a textbox when there is a value stored in memory but I figured it was easier to start with this part.
private void digitCalculate_Click(object sender, EventArgs e)
{
Button ButtonThatWasPushed = (Button)sender;
string ButtonText = ButtonThatWasPushed.Text;
decimal EndResult = 0;
decimal MemoryStore = 0;
if (ButtonText == "MC")
{
//Memory Clear
MemoryStore = 0;
return;
}
if (ButtonText == "MR")
{
//Memory Recall
txtDisplay.Text = MemoryStore.ToString();
return;
}
if (ButtonText == "MS")
{
// Memory subtract
MemoryStore -= EndResult;
return;
}
if (ButtonText == "M+")
{
// Memory add
MemoryStore += EndResult;
return;
}
}

You need to have Form level variable for decimal MemoryStore = 0; , since you have function level variable it will initialized to 0 when you click on digitCalculate button
decimal MemoryStore = 0;
decimal EndResult = 0;
public Form1()
{
InitializeComponent();
}
private void digitCalculate_Click(object sender, EventArgs e)
{
Button ButtonThatWasPushed = (Button)sender;
string ButtonText = ButtonThatWasPushed.Text;
//decimal EndResult = 0;
//decimal MemoryStore = 0;
And also note that
MC = Memory Clear sets the memory to 0
MR = Memory Recall uses the
number in memory
MS = Memory Store puts the number on the display into the memory
You nee to change "MS" logic and add "M-"
if (ButtonText == "MS")
{
MemoryStore = Decimal.Parse(txtDisplay.Text);
return;
}
if (ButtonText == "M-")
{
// Memory subtract
MemoryStore -= EndResult;
txtDisplay.Text = MemoryStore.ToString();
return;
}
if (ButtonText == "M+")
{
// Memory add
MemoryStore += EndResult;
txtDisplay.Text = MemoryStore.ToString();
return;
}

Just change the variable MemoryStore to a global variable. At the moment, it is being re-declared each time a button is pushed, meaning that the data is lost between button presses. Move it outside of the function, and it should work fine.

Related

Using function in ASP.NET web application

Excuse me guys, i'm a beginner in c# and needed help and some guidance in creating a calculator web app.
So i was given a task to create a calculator web app using the ASP.NET web application web form with the UI looking like this:
Calculator UI
The thing is, i made a mistake and made it using Windows Forms App (WFA) instead and i could get the calculator to work.
But when i tried to make the calculator using the ASP.NET web application web form the calculator won't work because somehow the variable that i set to run the method didn't get any value unlike when i run it in the WFA.
Here is my code:
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
bool lastpressedIsOperation;
string input = String.Empty;
protected void num_Click(object sender, EventArgs e)
{
Button button = sender as Button;
//this.display.Text = "";
input+=button.Text;
if (display.Text == "0" && display.Text != null)
{
display.Text = button.Text;
}
else
{
display.Text += button.Text;
}
}
protected void op_Click(object sender, EventArgs e)
{
Button button = sender as Button;
input+=button.Text;
if (display.Text == "0" && button.Text == "-" && display.Text != null)
{
display.Text = button.Text;
}
else
{
display.Text += button.Text;
}
}
protected void del_Click(object sender, EventArgs e)
{
//this.display.Text = input.ToString(0,input.Length);
}
protected void del_all_Click(object sender, EventArgs e)
{
this.display.Text = "0";
this.input = string.Empty;
}
private void enter_Click(object sender, EventArgs e)
{
string inFix = input;
string isValid = Validate(inFix);
string rpn = ConvertToPostFix(isValid);
string result = Convert.ToString(CalculateRPN(rpn));
this.display.Text = result;
input = result;
}
private static string Validate(string inFix)
{
StringBuilder newstring = new StringBuilder(inFix);
Stack<int> lb_index = new Stack<int>();//stack for left bracket index
Queue<int> rb_index = new Queue<int>();//stack for right bracket index
char temp = '#';
Console.WriteLine("temp: ", temp);
for (int i = 0; i < newstring.Length; i++)
{
if (newstring[i] == '(')
lb_index.Push(i);
else if (newstring[i] == ')')
rb_index.Enqueue(i);
Console.WriteLine("temp: {0}", temp);
if (newstring[i] == '-')//change unary - to ~
{
if (temp.IsOperator())
{
newstring[i] = '~';
}
}
temp = newstring[i];
}
if (lb_index.Count == rb_index.Count)
{
bool bracket_valid = true;
for (int i = 0; i < lb_index.Count; i++)
{
if (lb_index.Pop() > rb_index.Dequeue())
{
bracket_valid = false;
break;
}
}
if (bracket_valid != true)
{
newstring.Clear();
newstring.Append("Error, Bracket wrong");
}
}
else if (lb_index.Count < rb_index.Count || lb_index.Count > rb_index.Count)
{
newstring.Clear();
newstring.Append("Error, Bracket wrong");
}
Console.WriteLine("newstring = {0}", newstring);
return newstring.ToString();
}
The idea is i want to get the string from textbox after the user inputted the value using number and operation buttons and pressed the enter button.
The string is then validated first using Validate(inFix), then formatted into postfix ConvertToPostFix(isValid), which then calculated using CalculateRPN(rpn).
But i dont know why the isValid variable never get the value from Validate(inFix) which cause the other methods not working. Is there some difference on how to use the function in ASP Web app form? If so, how do i use method/function in this?
And is there any better way to implement this so i can fulfill my task?
I believe your problem is that you are setting:
string inFix = input;
In your
enter_Click
method.
Yet, the
input
variable is initialized to:
string input = String.Empty;
So, each time the form is loaded, i.e. on an initial load or a postback, the input variable is re-initialized to an empty string.
I'll not reinvent the post here, but to resolve this, you need to do something like:
Session["INPUT"] = input;
whenever input is modified, and do something like:
input = (string)Session["INPUT"];
To initialize the input variable on the page load.
If it is the initial page load, the input variable will be null (i.e. the session variable Session["INPUT"] does not exist).
Basically, what I am saying is that, while the asp.net session stores the state of controls on the forms, it does not save the state of your own class variables that you add to the page.

Re-Enabling Button Based on Condition (C#)

What I am trying to do is simple (I cannot figure it out of course). I am making a sample shop with an inventory system in Winform App format where if on the customer side the "Place Order" button is clicked it deducts from inventory; the amount deducted depends on the quantity of the item ordered. Anyway with this code,
private void button7_Click(object sender, EventArgs e)
button7.Enabled = true;
//Read in value
int qty = Convert.ToInt32(nudQuantity.Value);
if ((rdoSmallCup.Checked & rdoStraw.Checked) == true) {
//Removing four from inventory for strawberry after an order is made
InvStrawberry = InvStrawberry - (4 * qty);
if (InvStrawberry <= 0) {
button7.Enabled = false;
} else {
button7.Enabled = true;
}
label17.Text = Convert.ToString(InvStrawberry);
I am seeing that while it does compile with no errors once the inventory for strawberry has fallen past zero (it will actually be a negative value which I do not want but is another question for another time) the Place Order button ("Button 7") will be grayed out and unusable which is the goal but once inventory is added again this button is still unusable. Can someone explain how I can have this button re-enabled (even though I said it in the 'else' condition)?
Ron and Heretic's comments are right. You cannot access the code in Button7 click event handler once it has been 'disabled'. The only way to enable it again is from outside logic, say after you added additional items into the inventory, you can enable the button right after that.
Also you can can be simplify a bit:
private void button7_Click(object sender, EventArgs e)
//Read in value
int qty = Convert.ToInt32(nudQuantity.Value);
if ((rdoSmallCup.Checked & rdoStraw.Checked) == true) {
//Removing four from inventory for strawberry after an order is made
InvStrawberry = InvStrawberry - (4 * qty);
if (InvStrawberry <= 0)
button7.Enabled = false;
label17.Text = Convert.ToString(InvStrawberry);
...
This code will allow an infinite number of subtraction. Hence, you will need a control that will stop the subtraction when you go below zero.
private void button7_Click(object sender, EventArgs e){
// I have no idea why you have enabled the button here, mate
//Converting the quantity
int qty = Convert.ToInt32(nudQuantity.Value);
if((roSmallCup.Checked & rdoStraw.Checked) == true) {
//triggers when the Inventory of strawberry is more than zero
if( (InvStrawberry - (4 * qty)) > 0 ){
InvStrawberry = InvStrawberry - (4 * qty);
} else
{
button7.ENabled = false;
MessageBox.Show("We are out of inventory,Sorry!");
}
label17.Text = Convert.ToString(InvStrawberry);
}
}
If you want the button to possibly update every time that you change the value of InvStrawberry then the best option is to make a property for InvStrawberry and update the status of the button there. That cuts down the logic that you need to use right throughout your code.
Try this:
public class StrawberryForm : Form
{
private int _invStrawberry = 0;
private int InvStrawberry
{
get
{
return _invStrawberry;
}
set
{
_invStrawberry = value;
button7.Enabled = _invStrawberry > 0;
}
}
private void button7_Click(object sender, EventArgs e)
{
int qty = Convert.ToInt32(nudQuantity.Value);
if ((rdoSmallCup.Checked & rdoStraw.Checked) == true)
{
this.InvStrawberry -= 4 * qty;
label17.Text = Convert.ToString(this.InvStrawberry);
}
}
}
you need to move this:
if (InvStrawberry <= 0) {
button7.Enabled = false;
} else {
button7.Enabled = true;
}
to an Updae method or loop that will check it regularly, right now its in your click, and therefore will never get called to enable it again once it is disabled, since at that point you cant click on it.
also, say you have two variables, numberStrawberries representing youre remaining inventory, and lot representing the four strawberries you put in a purchase...
if(numberStrawberries >= lot){
//we have strawberries, and more at least 4 or more
numberStrawberries-=lot;
}else if(numberStrawberries!=0 && numberStrawberries < lot){
//we have strawberries but only (remaining)
//how many were short(how many we have is still in numberStrawberries)
int short = lot- numberStrawberries;
numberStrawberries=0;
}else{
//all out of strawberries
}

Calculate or Clear wont' work

I am working on a Windows Form. Every time I press Calculate or clear, nothing happens. The form loads but buttons won't work. Textboxes remain clear, with no values. Visual Studio doesn't recognize the code as a mistake. Any help?
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
int numberOfInvoices = 0;
decimal totalOfInvoices = 0m;
decimal invoiceAverage = 0m;
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal txtSubtotal = Convert.ToDecimal(txtEnterSubtotal.Text);
decimal discountPercent = .25m;
if (txtSubtotal >= 500)
{
discountPercent = .2m;
}
else if (txtSubtotal >= 250 && txtSubtotal < 500)
{
discountPercent = .15m;
}
else if (txtSubtotal >= 100 && txtSubtotal < 250)
{
discountPercent = .1m;
}
else
{
discountPercent = .0m;
}
decimal discountAmount = Math.Round(txtSubtotal * discountPercent, 2);
decimal invoiceTotal = txtSubtotal - discountAmount;
this.txtSubtotal.Text = txtSubtotal.ToString("c");
txtDiscountPercent.Text = discountPercent.ToString("p1");
txtDiscountAmount.Text = discountAmount.ToString("c");
txtTotal.Text = invoiceTotal.ToString("c");
numberOfInvoices++;
totalOfInvoices += invoiceTotal;
invoiceAverage = totalOfInvoices / numberOfInvoices;
txtNumberOfInvoices.Text = numberOfInvoices.ToString();
txtTotalOfInvoices.Text = totalOfInvoices.ToString("c");
txtInvoiceAverage.Text = invoiceAverage.ToString("c");
txtEnterSubtotal.Text = "";
txtEnterSubtotal.Focus();
}
private void btnClearTotals_Click(object sender, System.EventArgs e)
{
numberOfInvoices = 0;
totalOfInvoices = 0m;
invoiceAverage = 0m;
txtNumberOfInvoices.Text = "";
txtTotalOfInvoices.Text = "";
txtInvoiceAverage.Text = "";
txtEnterSubtotal.Focus();
}
}
}
I really appreciate your help, please let me know how I could improve.
Both your click handlers seem to work fine. I am guessing you don't have them connected to the button objects for some reason. Maybe you created them, saved the Form1.cs file, and then opened the Form in designer and hit undo or something like that.
You should be able to make them work again by opening the form in designer, double-clicking the button and move the code to the new method created by the designer.
Once connected, the Form1.Designer.cs should contain the following line:
this.btnCalculate.Click += new System.EventHandler(this.btnCalculate_Click);
and similar for the clear button.

increment how many times an image is displayed in a picturebox

I'm trying to display an image using a button click and increment a variable when a certain image is shown, but with the code below the variable num is always 0.
my code
int num = 0;
int i = 0;
int x = 0;
PictureBox[] pictureBoxs = new PictureBox[4];
Random rnd = new Random();
public UserControl1()
{
InitializeComponent();
pictureBoxs[0] = pbimg1;
pictureBoxs[1] = pbimg2;
pictureBoxs[2] = pbimg3;
pictureBoxs[3] = pbimg4;
x = rnd.Next(2);
}
public void displaypics()
{
pictureBoxs[i].Image = imageList1.Images[x];
}
private void btn2_Click(object sender, EventArgs e)
{
i=1;
displaypics();
if (pictureBoxs[i].Image == imageList1.Images[1])
{
num++;
}
if (num == 2)
{
tb1.Visible = true;
tb1.Text = "GAME OVER!" + num;
}
}
The reason is most likely that num is being instantiated to zero everytime the class is being instantiated
What happens when you set breakpoints and step through the code? Is the int set as 0, or does it contain the updated value?
I'm not sure what the context is in which that piece of code is used. So I guess what should solve this would be adding x = rnd.Next(2) to the btn2_Click method. Making it look like this:
private void btn2_Click(object sender, EventArgs e)
{
x = rnd.Next(2);
displaypics();
if (pictureBoxs[i].Image == imageList1.Images[1])
{
num++;
}
if (num == 2)
{
tb1.Visible = true;
tb1.Text = "GAME OVER!" + num;
}
i++;
}
Maybe you could give some more details on what that control should do/how it's used.

Calculation is wrong

What should happen
My exexcrise is it to prgramm a calculator which is able to do calculations in 'queue'.
Example:
User enters first number in txtZahl and then clicks one of the button. The needed calculation should be saved in the list numbers and txtZahl should be cleared. The user can now enter a new number and press a button etc.
When the user clicks on btnEqu the foreach should take every calculation from the list and do the calculation. If this is done the result should be displayed in txtZahl.
Problem
The calculations are not correct. For example I get 0.00 as result for 4-3.
I know that the idea with the extra class is not the best way, but I would like to keep it, to see what my teacher thinks about it.
Thank you for helping!
Code:
Form1.cs
double ergebniss = 0;
Boolean firstRun = true;
List<Rechnung> numbers = new List<Rechnung>();
Rechnung.RechenArt lastArt;
private void btnMinus_Click(object sender, EventArgs e)
{
if (isValid())
{
if (firstRun)
{
ergebniss = Convert.ToDouble(txtZahl.Text);
}
numbers.Add(new Rechnung(Convert.ToDouble(txtZahl.Text), Rechnung.RechenArt.Subtraktion));
lastArt = Rechnung.RechenArt.Subtraktion;
clearAndFocus();
}
}
private void btnEqu_Click(object sender, EventArgs e)
{
foreach (Rechnung r in numbers)
{
switch (r.getArt())
{
case Rechnung.RechenArt.Subtraktion:
{
ergebniss -= r.getNumber();
break;
}
}
}
txtZahl.Text = ergebniss.ToString("f2");
}
}
if (firstRun)
{
ergebniss = Convert.ToDouble(txtZahl.Text);
firstRun = false;
return;
}
first you forgot to
firstRun = false; after that
then I advice you to display just clean string
txtZahl.Text = ergebniss.ToString();
you also doesn't use lastArt variable don't know if that's necessary.

Categories