如何从用户输入 C# 填充数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/230454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:06:12  来源:igfitidea点击:

How to Fill an array from user input C#?

c#

提问by arin

What would be the best way to fill an array from user input?

从用户输入填充数组的最佳方法是什么?

Would a solution be showing a prompt message and then get the values from from the user?

解决方案是否会显示提示消息,然后从用户那里获取值?

采纳答案by Patrick Desjardins

string []answer = new string[10];
for(int i = 0;i<answer.length;i++)
{
    answer[i]= Console.ReadLine();
}

回答by Ed Altorfer

C# does not have a message box that will gather input, but you can use the Visual Basic input box instead.

C# 没有用于收集输入的消息框,但您可以改用 Visual Basic 输入框。

If you add a reference to "Microsoft Visual Basic .NET Runtime" and then insert:

如果添加对“Microsoft Visual Basic .NET 运行时”的引用,然后插入:

using Microsoft.VisualBasic;

You can do the following:

您可以执行以下操作:

List<string> responses = new List<string>();
string response = "";

while(!(response = Interaction.InputBox("Please enter your information",
                                        "Window Title",
                                        "Default Text",
                                        xPosition,
                                        yPosition)).equals(""))
{
   responses.Add(response);
}

responses.ToArray();

回答by Coderer

Could you clarify the question a bit? Are you trying to get a fixed number of answers from the user? What data type do you expect -- text, integers, floating-point decimal numbers? That makes a big difference.

你能把问题说清楚一点吗?您是否想从用户那里获得固定数量的答案?您期望什么数据类型——文本、整数、浮点十进制数?这有很大的不同。

If you wanted, for instance, an array of integers, you could ask the user to enter them separated by spaces or commas, then use

例如,如果您想要一个整数数组,您可以要求用户输入以空格或逗号分隔的它们,然后使用

string foo = Console.ReadLine();
string[] tokens = foo.Split(",");
List<int> nums = new List<int>();
int oneNum;
foreach(string s in tokens)
{
    if(Int32.TryParse(s, out oneNum))
        nums.Add(oneNum);
}

Of course, you don't necessarily have to go the extra step of converting to ints, but I thought it might help to show how you would.

当然,您不一定需要执行转换为整数的额外步骤,但我认为这可能有助于展示您将如何转换。

回答by Rune Grimstad

Add the input values to a List and when you are done use List.ToArray() to get an array with the values.

将输入值添加到列表中,完成后使用 List.ToArray() 获取包含值的数组。

回答by Stefan

Try:

尝试:

array[i] = Convert.ToDouble(Console.Readline());

You might also want to use double.TryParse() to make sure that the user didn't enter bogus text and handle that somehow.

您可能还想使用 double.TryParse() 来确保用户没有输入虚假文本并以某种方式进行处理。

回答by arin

I've done it finaly check it and if there is a better way tell me guys

我已经完成了最后检查,如果有更好的方法告诉我伙计们

    static void Main()
    {
        double[] array = new double[6];
        Console.WriteLine("Please Sir Enter 6 Floating numbers");
        for (int i = 0; i < 6; i++)
        {
            array[i] = Convert.ToDouble(Console.ReadLine());
        }

        double sum = 0;

        foreach (double d in array)
        {
            sum += d;
        }
        double average = sum / 6;
        Console.WriteLine("===============================================");
        Console.WriteLine("The Values you've entered are");
        Console.WriteLine("{0}{1,8}", "index", "value");
        for (int counter = 0; counter < 6; counter++)
            Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
        Console.WriteLine("===============================================");
        Console.WriteLine("The average is ;");
        Console.WriteLine(average);
        Console.WriteLine("===============================================");
        Console.WriteLine("would you like to search for a certain elemnt ? (enter yes or no)");
        string answer = Console.ReadLine();
        switch (answer)
        {
            case "yes":
                Console.WriteLine("===============================================");
                Console.WriteLine("please enter the array index you wish to get the value of it");
                int index = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("===============================================");
                Console.WriteLine("The Value of the selected index is:");
                Console.WriteLine(array[index]);
                break;

            case "no":
                Console.WriteLine("===============================================");
                Console.WriteLine("HAVE A NICE DAY SIR");
                break;
        }
    }

回答by Jon Skeet

It made a lot more sense to add this as an answer to arin's codethan to keep doing it in comments...

将其添加为arin 代码的答案比在评论中继续这样做更有意义......

1) Consider using decimal instead of double. It's more likely to give the answer the user expects. See http://pobox.com/~skeet/csharp/floatingpoint.htmland http://pobox.com/~skeet/csharp/decimal.htmlfor reasons why. Basically decimal works a lot closer to how humans think about numbers than double does. Double works more like how computers "naturally" think about numbers, which is why it's faster - but that's not relevant here.

1) 考虑使用十进制而不是双精度。更有可能给出用户期望的答案。请参阅http://pobox.com/~skeet/csharp/floatingpoint.htmlhttp://pobox.com/~skeet/csharp/decimal.html了解原因。基本上十进制比double更接近人类对数字的看法。Double 的工作方式更像是计算机“自然地”思考数字的方式,这就是它更快的原因——但这在这里无关紧要。

2) For user input, it's usually worth using a method which doesn't throw an exception on bad input - e.g. decimal.TryParse and int.TryParse. These return a Boolean value to say whether or not the parse succeeded, and use an outparameter to give the result. If you haven't started learning about outparameters yet, it might be worth ignoring this point for the moment.

2) 对于用户输入,通常值得使用一种不会在错误输入时引发异常的方法——例如decimal.TryParse 和int.TryParse。这些返回一个布尔值来说明解析是否成功,并使用一个out参数给出结果。如果您还没有开始学习out参数,那么暂时可以忽略这一点。

3) It's only a little point, but I think it's wise to have braces round all "for"/"if" (etc) bodies, so I'd change this:

3)这只是一点点,但我认为在所有“for”/“if”(等)主体周围使用大括号是明智的,所以我会改变这一点:

for (int counter = 0; counter < 6; counter++)
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);

to this:

对此:

for (int counter = 0; counter < 6; counter++)
{
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
}

It makes the block clearer, and means you don't accidentally write:

它使块更清晰,并且意味着您不会意外地编写:

for (int counter = 0; counter < 6; counter++)
    Console.WriteLine("{0,5}{1,8}", counter, array[counter]);
    Console.WriteLine("----"); // This isn't part of the for loop!

4) Your switch statement doesn't have a defaultcase - so if the user types anything other than "yes" or "no" it will just ignore them and quit. You might want to have something like:

4)您的 switch 语句没有default大小写 - 因此,如果用户键入“是”或“否”以外的任何内容,它只会忽略它们并退出。你可能想要这样的东西:

bool keepGoing = true;
while (keepGoing)
{
    switch (answer)
    {
        case "yes":
            Console.WriteLine("===============================================");
            Console.WriteLine("please enter the array index you wish to get the value of it");
            int index = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("===============================================");
            Console.WriteLine("The Value of the selected index is:");
            Console.WriteLine(array[index]);
            keepGoing = false;
            break;

        case "no":
            Console.WriteLine("===============================================");
            Console.WriteLine("HAVE A NICE DAY SIR");
            keepGoing = false;
            break;

        default:
            Console.WriteLine("Sorry, I didn't understand that. Please enter yes or no");
            break;
    }
}

5) When you've started learning about LINQ, you might want to come back to this and replace your for loop which sums the input as just:

5) 当你开始学习 LINQ 时,你可能想回到这个并替换你的 for 循环,它将输入总结为:

// Or decimal, of course, if you've made the earlier selected change
double sum = input.Sum();

Again, this is fairly advanced - don't worry about it for now!

同样,这是相当先进的 - 现在不要担心!

回答by Jon Skeet

of course....Console.ReadLine always return string....so you have to convert type string to double

当然....Console.ReadLine 总是返回字符串....所以你必须将类型字符串转换为双精度

array[i]=double.Parse(Console.ReadLine());

array[i]=double.Parse(Console.ReadLine());

回答by Jon Skeet

readline is for string.. just use read

readline 用于字符串.. 只需使用 read