简体   繁体   English

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

[英]How to Fill an array from user input C#?

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? 解决方案是否会显示提示消息,然后从用户获取值?

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

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. 当然,你不一定要采取转换为整数的额外步骤,但我认为这可能有助于展示你的意愿。

It made a lot more sense to add this as an answer to arin's code than to keep doing it in comments... 将此作为arin代码的答案添加比在评论中继续这样做更有意义...

1) Consider using decimal instead of double. 1)考虑使用decimal而不是double。 It's more likely to give the answer the user expects. 它更有可能给出用户期望的答案。 See http://pobox.com/~skeet/csharp/floatingpoint.html and http://pobox.com/~skeet/csharp/decimal.html for reasons why. 有关原因,请参见http://pobox.com/~skeet/csharp/floatingpoint.htmlhttp://pobox.com/~skeet/csharp/decimal.html 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. Double更像是计算机“自然地”思考数字的原因,这就是为什么它更快 - 但这与此无关。

2) For user input, it's usually worth using a method which doesn't throw an exception on bad input - eg decimal.TryParse and int.TryParse. 2)对于用户输入,通常值得使用一种不会在错误输入上抛出异常的方法 - 例如decimal.TryParse和int.TryParse。 These return a Boolean value to say whether or not the parse succeeded, and use an out parameter to give the result. 这些返回一个布尔值来表示解析是否成功,并使用out参数来给出结果。 If you haven't started learning about out parameters yet, it might be worth ignoring this point for the moment. 如果你还没有开始学习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 default case - so if the user types anything other than "yes" or "no" it will just ignore them and quit. 4)你的switch语句没有default情况 - 所以如果用户键入“yes”或“no”以外的任何内容,它将忽略它们并退出。 You might want to have something like: 你可能希望得到类似的东西:

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! 同样,这是相当先进的 - 现在不要担心它!

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();

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()来确保用户没有输入伪造文本并以某种方式处理。

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;
        }
    }

readline是for string ..只需使用read

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

of course....Console.ReadLine always return string....so you have to convert type string to double 当然.... Console.ReadLine总是返回字符串....所以你必须将类型字符串转换为double

array[i]=double.Parse(Console.ReadLine()); 阵列[I] = double.Parse(到Console.ReadLine());

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

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