【问题标题】:Array which stores information from user input存储来自用户输入的信息的数组
【发布时间】:2021-01-22 08:18:05
【问题描述】:

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

【问题讨论】:

  • 大声朗读您的代码:创建一个字符串数组,长度为 2,索引 0 和 1。然后循环两次(第一次索引 = 0,然后索引 = 1)。第一次通过时,您提示“第一个朋友”,将结果放入friends[0],然后再次提示(第二个朋友),然后将结果放入friends[0],覆盖那里的内容。然后将friends 写入控制台并等待用户输入。但是,friends 是一个数组,如果将其转换为字符串,则得到的只是类型的名称(字符串数组)。然后你再做一次,提示两次并写入/覆盖friends[1]

标签: c# arrays user-input


【解决方案1】:

除了一些小问题,你几乎就在那里

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!");

输出

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

These are your friends 
bob
john
Game Over!

值得注意的是,List&lt;T&gt; 非常适合这些类型的情况,您不必担心索引,只需扩展和添加使用List.Add(something)

加入列表

【讨论】:

  • 如果您使用List&lt;string&gt;,您可以输入 N 个朋友,而不仅仅是两个。你所做的是将Console.ReadLine()读入一个变量(比如var newFriendName = Console.ReadLine();。如果变量不是IsNullOrEmpty(查找),那么你friendsList.Add(newFriendName)。如果它为空或空,那么你计算数据进入完成,跳出第一个循环。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-24
  • 1970-01-01
  • 2017-10-12
  • 2012-04-28
  • 1970-01-01
  • 1970-01-01
  • 2017-01-07
相关资源
最近更新 更多