首页 > 解决方案 > 存储来自用户输入的信息的数组

问题描述

C# - 我正在尝试编写一个数组来存储来自用户输入的信息。在我的代码中,我使用了一个我命名为朋友的字符串数组,然后我继续使用此方法https://stackoverflow.com/a/230463/14764548。最后,我希望控制台应用程序将存储的信息显示为数组。

enter code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;

namespace arraysTut
{
    class arraysTut
    {
        static void Main()

            string[] friends = new string[2];
            for(string i=0;i<friends.length;i++)
            {
                Console.WriteLine("First Friend: ");
                friends[i] = Console.ReadLine();
            
                Console.WriteLine("Second Friend: ");
                friends[i] = Console.ReadLine();
                
                Console.WriteLine(friends);

                Console.ReadLine();
            }
    }
}

标签: c#arraysuser-input

解决方案


Apart from a few minor issues, you were nearly there

var friends = new string[2];

for (var i = 0; i < friends.Length; i++)
{
   Console.Write($"Enter friend ({i + 1}) : ");
   friends[i] = Console.ReadLine();
}

Console.WriteLine();
Console.WriteLine("These are your friends");

foreach (var friend in friends)
   Console.WriteLine(friend);

Console.WriteLine("Game Over!");

Output

Enter friend (1) : bob
Enter friend (2) : john

These are your friends 
bob
john
Game Over!

It's worth noting, List<T> are good a match for these types of situations, you don't have to worry about indexes, and can just expand and add to the list with List.Add(something)


推荐阅读