none
Won't add to stack RRS feed

  • Question

  • Hi everyone! I'm not so good with C# but I have this assignment that I am stuck on. The method is suppose to correct brackets and other characters like "[" and "{" and then tell the user if the string is correct or not. This is a correct string "(({}))" and this is not "(([{]))". 
    The thing is that my if-statements won't work and won't add the char into the stack and I can't figure out why it is like that.
    Could someone please tell me why this is wrong so that I can fix it? Oh, and note that the code is not done yet.

    private static void CheckParentheses()
            {
                Stack<char> stacken = new Stack<char>();
                Console.WriteLine("Please enter a mening or a word containing brackets or simular symbols.");
                string input = "";
                input = Console.ReadLine();

                foreach (char A in input)
                {
                    if (input == "(" || input == "[" || input == "{")
                    {
                        stacken.Push(A);
                    }

                    if (input == ")")
                    {
                        if (stacken.Last() == '(')
                        {
                            stacken.Pop();
                        }
                        else
                        {
                            stacken.Push(A);
                        }
                    }

                    if (input == "]")
                    {
                        if (stacken.Last() == '[')
                        {
                            stacken.Pop();
                        }
                        else
                        {
                            stacken.Push(A);
                        }
                    }

                    if (input == "}")
                    {
                        if (stacken.Last() == '{')
                        {
                            stacken.Pop();
                        }
                        else
                        {
                            stacken.Push(A);
                        }
                    }

                    else
                    {

                    }

                }
                while (input != "") ;

            }

    Saturday, March 31, 2012 12:31 PM

Answers

  • You want to go through all characters of input, so you wrote
    foreach (char A in input)
    but then you are using input inside? I think you want to replace all Input inside the foreach with A because you want to check if the current char is what you got.

    And then you have a while at the end - but inside the while Loop you do nothing so it is an endless Loop - you want to remove that, too.

    With Kind regards,

    Konrad

    • Marked as answer by chumic Saturday, March 31, 2012 1:44 PM
    Saturday, March 31, 2012 12:45 PM