简体   繁体   English

c# Console.WriteLine();

[英]c# Console.WriteLine();

In C#, after I write Console.WriteLine() and I'm asked to enter several values, can I get them all in one method?在 C# 中,在我编写Console.WriteLine()并且我被要求输入多个值后,我可以用一种方法获取它们吗? For example:例如:

double a, b, c = 0;
Console.WriteLine("please enter the values of:\n a value:\n b value: \n c value:");

thanks for the help (:谢谢您的帮助 (:

There's no BCL methods for this specific functionality, but you could use a helper function to collect these without too much repetition.没有针对此特定功能的 BCL 方法,但您可以使用辅助函数来收集这些内容,而无需过多重复。

static void Main(string[] args)
{
    string RequestInput(string variableName)
    {
        Console.WriteLine($"{variableName}:");
        return Console.ReadLine();
    }

    Console.WriteLine("please enter the values of:");
    var a = double.Parse(RequestInput("a"));
    var b = double.Parse(RequestInput("b"));
    var c = double.Parse(RequestInput("c"));

}

You could do something like the following, which assumes that the user will enter a string in the console like "2.3 3.4 4.5" .您可以执行以下操作,假设用户将在控制台中输入一个字符串,例如"2.3 3.4 4.5" You may need to do some checking to make sure the input is correct.您可能需要进行一些检查以确保输入正确。

double  a = 0.0, b = 0.0, c = 0.0;
Console.WriteLine("please enter the values of: a b c");

string input = Console.ReadLine();
string[] inputParts = input.Split(' ');

if (inputParts.Length > 0 && inputParts[0] != null) 
{
    Double.TryParse(inputParts[0], out a);
}

if (inputParts.Length > 1 && inputParts[1] != null) 
{
    Double.TryParse(inputParts[1], out b);
}

if (inputParts.Length > 2 && inputParts[2] != null) 
{
    Double.TryParse(inputParts[2], out c);
}

Console.WriteLine($"a: {a.ToString()}");
Console.WriteLine($"b: {b.ToString()}");
Console.WriteLine($"c: {c.ToString()}");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM