应用程序无法正常工作C#

时间:2016-10-14 19:06:12

标签: c# loops switch-statement

我的代码没有将响应存储为用户输入。每次我到这里都会跳到else语句。那么它总和为50?当我存储输入时,如第一个数字的值= 2和第二个值= 3。 我正在家里上课,我已经工作了几个小时试图弄清楚为什么我的代码不能正常工作。 C#,下面:

                    Console.Write("Would you like to stop adding here (a) or add another number (b)? ");
                    bool stopOrContinueAdding = true;
                    do
                    {
                            string inputMoreNumbers = Console.ReadLine();
                            switch (inputMoreNumbers.ToLower())
                            {
                                case "a":
                                    inputMoreNumbers = "a";
                                    stopOrContinueAdding = false;
                                    break;
                                case "b":
                                    inputMoreNumbers = "b";
                                    stopOrContinueAdding = true;
                                    break;
                                default:
                                    stopOrContinueAdding = false;
                                    break;
                            }
                            if (stopOrContinueAdding == false)
                            {
                                int sum = aNum.Sum();
                                Console.WriteLine("Here is the sum of your numbers: " + sum );
                                System.Threading.Thread.Sleep(4000);
                                Console.WriteLine("Redirecting to main menu...");
                                System.Threading.Thread.Sleep(2000);
                                Console.Clear();
                                Console.Write("Addition(a), Subraction(s), Multiplication(x), or Division(d)? ");
                                isInputValid = false;
                            }
                            else
                            {
                                Console.Clear();
                                Console.Write("Value of next number: ");
                                number++;
                                aNum[number - 1] = Convert.ToInt32(Console.Read());
                                Console.Write("Would you like to stop adding here (a) or add another number (b)? ");
                            }
                        } while (stopOrContinueAdding != true) ;

我不完全确定我哪里出错了。我想了解更多:(

谢谢!

1 个答案:

答案 0 :(得分:1)

在您的加法计算器中,更改以下行:

aNum[number - 1] = Convert.ToInt32(Console.Read());
从Console.Read()到Console.ReadLine()的

似乎解决了这个问题。 ReadLine()将阻止执行,直到Enter被命中 - Read()不会......所以当你输入你的第二个数字并按Enter键时,它会执行你的下一个ReadLine()语句(你期望“a”或“b” “取决于他们是否想要继续)作为空白字符串。