C#如何停止控制台程序等待下一行输入?

4
我刚刚开始编写一个控制台程序,用户将输入一个整数。它应该继续要求输入整数,直到他们输入“ok”。当他们输入“ok”时,它应该将他们输入的所有数字加起来。
我遇到的问题是,当它要求用户输入时,我输入一个数字并按回车键。然后它就移到下一行并等待再次输入。在下一行输入一个数字可以使程序继续工作。如何让程序从第一个输入继续运行?
以下是代码,希望我的问题有意义。
class Program
{
    static void Main(string[] args)
    {
        bool tag = true;
        List<int> numbers = new List<int>();
        while (tag == true)
        {
            Console.Write("Please enter a number or 'ok' to end: ");
            if (Console.ReadLine().Equals("ok"))
            {
                tag = false;
            }
            else
            {
                int numb = Int32.Parse(Console.ReadLine());
                numbers.Add(numb);
            }
        }

        int total = 0;
        foreach (int n in numbers)
        {
            total = total + n;
        }
        Console.WriteLine("All numbers added together equals: " + total);
    }
}

1
你知道吗...这看起来像是一个学生作业,但很高兴看到你在网站上的第一篇帖子中开始展示了完整的代码示例,展示了你尝试过什么以及你的思考过程。很少有人这样做,恭喜。 - Pedro Lorentz
谢谢。这是我正在学习的在线课程中的一项练习。 - joehelsing
3个回答

2

在每次迭代中,您只应从控制台读取一次。

//[...]
while (tag == true)
{
    Console.Write("Please enter a number or 'ok' to end: ");
    var input = Console.ReadLine();
    if (input.Equals("ok"))
    {
        tag = false;
    }
    else
    {
        int numb = Int32.Parse(input);
        numbers.Add(numb);
    }
}
//[...]

每次调用Console.ReadLine,用户都必须输入内容——因为你要调用它一次来与“Ok”进行比较,再调用一次来解析,所以用户需要两次输入数字。
如果将输入作为循环条件,甚至可以进一步省略tag变量:
var input = "";
var numbers = new List<int>();
while((input = Console.ReadLine()) != "ok")
{
    numbers.Add(int.Parse(input));
}

如果用户输入的既不是“ok”,也不是有效的整数,则所有这些都没有任何错误处理。为此,您应该查看int32.TryParse


1

为了增加指定问题的可能解决方案(将递归与混合物结合起来),仅做补充:

class Program
{
    private static List<int> numbers = new List<int>();
    private static int Prompt()
    {
        //1. Promt the user for input
        Console.Write("Please enter a number or 'ok' to end: ");
        var input = Console.ReadLine().ToLower();
        int number = 0;
        if (input.Equals("ok"))
        {
            //2. Do nothing and end the Program
        }
        else
        {
            //3. Ty to parse to int and append to the list
            if(int.TryParse(input, out number))
            {
                //4. Add the number to the list (no more needed for sum but still if you want to maintain the order of numbers added :))
                numbers.Add(number);                    
            }
            else
            {
                //5. In case of junk input
                Console.WriteLine("Invalid input.");
            }
            number += Prompt();
        }
        return number;
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Total of the Inout Numbers: " + Prompt());

        Console.ReadKey();
    }
}

希望这有所帮助并提供了另一种视角 :)

0

所以,当我完成我的回答时(我决定让Visual Studio更新...),已经有一个回答指出了问题(多次从控制台读取而不是将结果存储在变量中)。我只是决定发布代码,这样你就可以看到另一种可能对你有效的方法(不存储所有数字)。

正如你所看到的,我忽略了任何不是int或OK的内容。

class Program
 {
     static void Main(string[] args)
     {
         var total = 0;
         Console.WriteLine("Please enter a number or 'ok' to end: ");
         bool numberRead;
         string line;
         do
         {
            line = Console.ReadLine();
            if(numberRead = int.TryParse(line, out int number))
                total += number;
         } while (numberRead && line?.ToLower() != "ok");

         Console.WriteLine("All numbers added together equals: " + total);
     }
 }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接