0

So I want to do my first Calculator but it does only do addition besides that whenever I use the point let's say 2.2 * 2.2 the whole thing crashes and I didn't figure out what I did wrong. Here is the code for it.

using System;
using System.Windows.Forms;

namespace Calculator
{
    public partial class Form1 : Form
    {
        Double resultValue = 0;
        String operationPerformed = "";
        bool isOperationPerformed = false;
        

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void Button_Click(object sender, EventArgs e)
        {
            if ((textBox_Result.Text == "0") || (isOperationPerformed) )
                textBox_Result.Clear();

            isOperationPerformed = false;
            Button button = (Button)sender;

            if(button.Text==".")
            {
                if(!textBox_Result.Text.Contains("."))
                    textBox_Result.Text = textBox_Result.Text + button.Text;


            }else
            

            textBox_Result.Text = textBox_Result.Text + button.Text;
        }

        private void Operator_Click(object sender, EventArgs e)
        {
            Button button = (Button)sender;

            if (resultValue != 0)
            {
                buttonEquals.PerformClick();
                operationPerformed = button.Text;
                resultValue = Double.Parse(textBox_Result.Text);
                labelCurrentOperation.Text = resultValue + " " + operationPerformed;
                isOperationPerformed = true;

            }
            else
            {


                operationPerformed = button.Text;
                resultValue = Double.Parse(textBox_Result.Text);
                labelCurrentOperation.Text = resultValue + " " + operationPerformed;
                isOperationPerformed = true;
            }
        }

        private void buttonClearEntry_Click(object sender, EventArgs e)
        {
            textBox_Result.Text = "0";
        }

        private void buttonClear_Click(object sender, EventArgs e)
        {
            textBox_Result.Text = "0";
            resultValue = 0;
        }

        private void buttonEquals_Click(object sender, EventArgs e)
        {
            switch(operationPerformed)
            {
                case "+":
                    textBox_Result.Text = (resultValue + Double.Parse(textBox_Result.Text)).ToString();
                    break;

                case "-":
                    textBox_Result.Text = (resultValue + Double.Parse(textBox_Result.Text)).ToString();
                    break;

                case "x":
                    textBox_Result.Text = (resultValue + Double.Parse(textBox_Result.Text)).ToString();
                    break;

                case "÷":
                    textBox_Result.Text = (resultValue + Double.Parse(textBox_Result.Text)).ToString();
                    break;
                   default:
                    break;

            }

            resultValue = Double.Parse(textBox_Result.Text);
            labelCurrentOperation.Text = " ";
        }
    }
}
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
H4DES
  • 17
  • 2
  • 1
    Please provide a minimal reproducible example. This code is much longer than is necessary for this question. – M-Chen-3 Feb 09 '21 at 17:54
  • I left it all just in case there is some error with the whole code – H4DES Feb 09 '21 at 18:02
  • 1
    what is the error returned? It would be more helpful to know what the exception is and where it is thrown. – Adam Feb 09 '21 at 18:05
  • The error is input string was not in a correct format. in the operator click if statement : resultValue = Double.Parse(textBox_Result.Text); . I tried to remove the line but didn't work too – H4DES Feb 09 '21 at 18:09
  • I created a simple test program with your code. It works fine unless the user only has "." as the input number. In this case, the parse function fails as "." is not a number. – Adam Feb 09 '21 at 18:29
  • It's set ". " to limit the user from typing more than one point besides that if I tried to multiply two numbers it just performs addition the same thing with divide. – H4DES Feb 09 '21 at 18:36
  • Please add an explanation of what every click method does and what button(s) are connected to them - you seem to have extra redundant methods. – NetMage Feb 09 '21 at 19:54
  • @NetMage in button_Click the buttons that are connected are (1,2,3,4,5,6,7,8,9,0, . ). In the operator_Click the buttons that are connected are (/, + , - , * ). In the button clear entry (CE), in the buttonClear_Click(C). I have the form_ load and label1_Click empty because I miss clicked on the label and it created an empty method and when I tried to delete it the calculator doesn't work and tells me to revert the changes. – H4DES Feb 09 '21 at 20:17
  • Your code looks okay to me - I think you must have something unexpected in one of your `button.Text` values. – NetMage Feb 09 '21 at 20:47
  • You can view/change what events are hooked to objects in visual studio by selecting events tab in visual studio, scrolling to the event and clicking on combo box to changed hooked event, double click to create event (if not already hooked) or right click and remove handler. – Adam Feb 09 '21 at 20:52
  • @Adam Yes I do get the same error – H4DES Feb 09 '21 at 21:11
  • It may be related to the environment culture setting. Try using `Double.Parse(textBox_Result.Text, System.Globalization.CultureInfo.InvariantCulture)` – Adam Feb 09 '21 at 21:17
  • what is the environmet culture setting?@Adam – H4DES Feb 09 '21 at 21:24
  • It is the culture C# uses to convert between numbers and strings. It is set based on the computer's culture settings. – Adam Feb 09 '21 at 21:32
  • @Adam I was curious because it worked but whenever I divide it or multiple with the same number I get an error in the switch statement – H4DES Feb 09 '21 at 21:35
  • This may be related to the double to string conversion, try replacing `.ToString()` with `.ToString(System.Globalization.CultureInfo.InvariantCulture)` – Adam Feb 09 '21 at 21:54
  • @Adam It didn't work – H4DES Feb 09 '21 at 21:58
  • I've updated my answer to change all conversions to use invariant culture. If it fixed initial format exception, I'm not sure why it didn't fix all. – Adam Feb 09 '21 at 22:17
  • @Adam I will try again, I appreciate your help a lot. Thank you – H4DES Feb 09 '21 at 22:25

1 Answers1

1

The issue is you are not catching format exception of Double.Parse function. It is throwing an exception when it is passed the string ".". Below code corrects this issue by replacing "." with "0". I've also added a catch to detect division by zero, as an example.

private void Operator_Click(object sender, EventArgs e)
        {
            Button button = (Button)sender;

            if (textBox_Result.Text == ".") textBox_Result.Text = "0";

            if (resultValue != 0)
            {
                buttonEquals.PerformClick();
                operationPerformed = button.Text;
                resultValue = Double.Parse(textBox_Result.Text, System.Globalization.CultureInfo.InvariantCulture);
                labelCurrentOperation.Text = resultValue + " " + operationPerformed;
                isOperationPerformed = true;

            }
            else
            {
                operationPerformed = button.Text;
                resultValue = Double.Parse(textBox_Result.Text, System.Globalization.CultureInfo.InvariantCulture);
                labelCurrentOperation.Text = resultValue + " " + operationPerformed;
                isOperationPerformed = true;
            }
        }

 private void buttonEquals_Click(object sender, EventArgs e)
        {
            if (textBox_Result.Text == ".") textBox_Result.Text = "0";

            switch(operationPerformed)
            {
                case "+":
                    textBox_Result.Text = (resultValue + Double.Parse(textBox_Result.Text, System.Globalization.CultureInfo.InvariantCulture)).ToString(System.Globalization.CultureInfo.InvariantCulture);
                    break;

                case "-":
                    textBox_Result.Text = (resultValue - Double.Parse(textBox_Result.Text, System.Globalization.CultureInfo.InvariantCulture)).ToString(System.Globalization.CultureInfo.InvariantCulture);
                    break;

                case "x":
                    textBox_Result.Text = (resultValue * Double.Parse(textBox_Result.Text, System.Globalization.CultureInfo.InvariantCulture)).ToString(System.Globalization.CultureInfo.InvariantCulture);
                    break;

                case "÷":
                    // check for divide by 0
                    double check = Double.Parse(textBox_Result.Text, System.Globalization.CultureInfo.InvariantCulture);
                    if (check != 0)
                    {
                        textBox_Result.Text = (resultValue / check).ToString(System.Globalization.CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        MessageBox.Show("divide by zero!");
                    }
                    break;
            }

            resultValue = Double.Parse(textBox_Result.Text, System.Globalization.CultureInfo.InvariantCulture);
            labelCurrentOperation.Text = " ";
        }
Adam
  • 562
  • 2
  • 15
  • I did exactly the same but I got again the same error but now in this line in else resultValue = Double.Parse(textBox_Result.Text), and the same error input string was not in a correct format – H4DES Feb 09 '21 at 19:30
  • Could you possibly have a space in the text of one of your buttons? When I changed my "2" button's text to "2 " it also caused this exception as "2 .2 " is not a valid number. – Adam Feb 09 '21 at 19:38
  • nope, I checked every button there are no spaces – H4DES Feb 09 '21 at 19:44
  • Is textBox_Result.Text initialized to "0" or ""? I initialized it to "0". What is the value of textBox_Result.Text when the error is thrown? – Adam Feb 09 '21 at 19:50
  • Do you mean its text? if so it is set to 0 – H4DES Feb 09 '21 at 19:54
  • I do only have the text set to 0 nothing else, it doesn't give me a value, when I run for example if I press 2.2 * 2.2 the calculator shuts down and it gives me an error in the else part of the operator click in the line resultValue = Double.Parse(textBox_Result.Text); and it says that Input string was not in a correct format – H4DES Feb 09 '21 at 20:04
  • 1
    On the line before the error, add `MessageBox.Show($"\"{textBox_Result.Text}\"");`. This will show message box with text in quotes. – Adam Feb 09 '21 at 20:44
  • it did show the number that I typed but after that, I got the error, would you like to see the details of it so I can copy it? – H4DES Feb 09 '21 at 20:48
  • System.FormatException HResult=0x80131537 Message=Input string was not in a correct format. Source=mscorlib StackTrace: at System.Number.ParseDouble(String value, NumberStyles options, NumberFormatInfo numfmt) at System.Double.Parse(String s) at Calculator.Form1.Operator_Click(Object sender, EventArgs e) in C:\projects\c#\CAlculator\Calculator\Calculator\Form1.cs:line 60 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) – H4DES Feb 09 '21 at 20:54
  • at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam,IntPtr lparam) at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) – H4DES Feb 09 '21 at 20:54
  • at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at Calculator.Program.Main() in C:\projects\c#\CAlculator\Calculator\Calculator\Program.cs:line 19 – H4DES Feb 09 '21 at 20:54
  • This exception was originally thrown at this call stack: [External Code] Calculator.Form1.Operator_Click(object, System.EventArgs) in Form1.cs [External Code] Calculator.Program.Main() in Program.cs – H4DES Feb 09 '21 at 20:55
  • that's it, sorry for being so long but I can't paste it all – H4DES Feb 09 '21 at 20:55
  • what was in the message box? – Adam Feb 09 '21 at 20:55
  • 2.2 because I typed that in – H4DES Feb 09 '21 at 20:57