-2

I tried to create a small calculator and everything worked just fine. I could do every operation without an error. Then I tried to improve some things and add some. Out of a sudden the original Part does not work anymore and i get the Error:[ System.FormatException: "Input string was not in a correct format." ] every time i try to substract, multiply or divide.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Calculator_V2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void OnKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                answer.Text = Calculate(textBox.Text);
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string s_button = sender.ToString();
            textBox.Text = textBox.Text + s_button.Substring(s_button.Length - 1);
        }


        public string Calculate(string text)
        {
            double finalAnswer = AddAndSubstract(text);

            return finalAnswer.ToString();


        }
        public double AddAndSubstract(string text1)
        {
            string[] text = text1.Split('-');
            List<string> textList = new List<string>();

            for (int i = 0; i < text.Length; i++)
            {
                textList.Add(text[i]);
                if (i != text.Length - 1)
                {
                    textList.Add("-");
                }
                textList.Add("-");
            }

            for (int i = 0; i < textList.Count; i++)
            {
                if (textList[i].Contains('+') && textList[i].Length > 1)
                {

                    string[] testPart = textList[i].Split('+');

                    textList.RemoveAt(i);

                    for (int j = testPart.Length - 1; j >= 0; j--)
                    {
                        textList.Insert(i, testPart[j]);
                        if (j != 0)
                        {
                            textList.Insert(i, "+");
                        }

                    }
                }

            }
            double total;
            if (textList[0].Contains("*") || textList[0].Contains("/"))
            {
                total = DivideAndMultiply(textList[0]);
                return total;
            }
            else
            {
                total = Convert.ToDouble(textList[0]);


                for (int i = 2; i < textList.Count; i += 2)
                {
                    if (textList[i - 1] == "-")
                    {
                        total = total - DivideAndMultiply(textList[i]);
                    }
                    else if (textList[i - 1] == "+")
                    {
                        total = total + DivideAndMultiply(textList[i]);
                    }


                }


                return total;
            }
        }

        public double DivideAndMultiply(string text1)
        {
            string[] text = text1.Split('*');
            List<string> textList = new List<string>();

            for (int i = 0; i < text.Length; i++)
            {
                textList.Add(text[i]);
                if (i != text.Length - 1)
                {
                    textList.Add("*");
                }
                textList.Add("*");
            }

            for (int i = 0; i < textList.Count; i++)
            {
                if (textList[i].Contains('/') && textList[i].Length > 1)
                {

                    string[] testPart = textList[i].Split('/');

                    textList.RemoveAt(i);

                    for (int j = testPart.Length - 1; j >= 0; j--)
                    {
                        textList.Insert(i, testPart[j]);
                        if (j != 0)
                        {
                            textList.Insert(i, "/");
                        }

                    }
                }

            }


            double total = Convert.ToDouble(textList[0]);

            for (int i = 2; i < textList.Count; i += 2)
            {
                if (textList[i - 1] == "/")
                {
                    total = total / Convert.ToDouble(textList[i]);
                }
                else if (textList[i - 1] == "*")
                {
                    total = total * Convert.ToDouble(textList[i]);
                }


            }


            return total;

        }



        private void Button_Click_C(object sender, RoutedEventArgs e)
        {
            double finalAnswer = 0;

            answer.Text = "";
            textBox.Text = "";
        }

        private void Button_Click_zahl(object sender, RoutedEventArgs e)
        {
            string s_button = sender.ToString();
            textBox.Text = textBox.Text + s_button.Substring(s_button.Length - 1);

        }

        private void Button_Click_equals(object sender, RoutedEventArgs e)
        {


                answer.Text = RemoveBrackets(textBox.Text);




        }

        public string RemoveBrackets(string text)
        {
            while (text.Contains('(') && text.Contains(')'))
            {
                int openIndex = 0;
                int closeIndex = 0;

                for (int i = 0; i < text.Length; i++)
                {
                    if (text[i] == '(')
                    {
                        openIndex = i;
                    }

                    if (text[i] == ')')
                    {
                        closeIndex = i;

                        text = text.Remove(openIndex,closeIndex-openIndex +1).Insert(openIndex,ResolveBrackets(openIndex, closeIndex, text));

                        break;
                    }
                }
            }



            for (int i = 1; i < text.Length; i++)
            {
                if (text[i] == '-' && (text[i]-1=='*' || text[i] - 1 == '/'))
                {
                    for (int j=i-1; j>=0; j++)
                    {
                        if (text[j] == '+')
                        {
                            StringBuilder text1 = new StringBuilder(text);
                            text1[j] = '-';
                            text = text1.ToString();
                            text = text.Remove(i, 1);
                            break;
                        }
                        else if (text[j] == '-')
                        {
                            StringBuilder text1 = new StringBuilder(text);
                            text1[j] = '+';
                            text = text1.ToString();
                            text = text.Remove(i, 1);
                            break;
                        }
                    }

                }
            }

            if (text[0] == '-') //für Fehler wenn - als erste Ziffer
            {
                text = '0' + text;
            }
            return Calculate(text);
        }

        public string ResolveBrackets(int openIndex, int closeIndex, string text)
        {
            string bracketAnswer = Calculate(text.Substring(openIndex +1, closeIndex -1));

            return bracketAnswer;
        }
    }


}
  • 1
    There is about a bunch of code in your question. Where does the error occur ? – Cid Jan 29 '20 at 15:18
  • Which line throws the exception? What is the runtime value of each relevant variable at that time? (Basically, what string value are you trying to convert into what other data type?) – David Jan 29 '20 at 15:20
  • This has been done countless of times before. Why are you trying to reinvent the wheel instead of using something premade/documented/error validated ? – Franck Jan 29 '20 at 15:20
  • 4
    @Franck for learning purposes obviously... – terrencep Jan 29 '20 at 15:22
  • 2
    A good opportunity to learn about the built-in Debugger. – Klaus Gütter Jan 29 '20 at 15:26
  • ya set some break points or at least post a stack trace. – terrencep Jan 29 '20 at 15:31
  • https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems – René Vogt Jan 29 '20 at 15:31
  • This exception is typically thrown by `Convert.ToDouble()` when - well - your input string is not in a correct format. That could mean that there is a wrong decimal point (e.g. a comma instead of a point) or a - or + you forgot to parse or something else instead of digits. – René Vogt Jan 29 '20 at 15:34

2 Answers2

0

Because you probably add the minus character twice

            if (i != text.Length - 1)
            {
                textList.Add("-");
            }
            textList.Add("-");

Then, when you loop in step of 2

for (int i = 2; i < textList.Count; i += 2)

You don't have [number] [sign] [number] [sign] anymore.

I suggest you look and the items in your list to see the problem. I would also suggest that you split your logic into smaller methods that could individually be tested.

the_lotus
  • 12,668
  • 3
  • 36
  • 53
0

i think the problem is your use of

double total = Convert.ToDouble(textList[0]);

in DivideAndMultiply

First of all it's best practice to test if the string is null or empty using String.IsNullOrEmpty(textList[0]); and use Double.TryParse instead of convert.

terrencep
  • 675
  • 5
  • 16