我正在制作日历。在这里,我想在会议中添加成员。在每个名字之后我想按Enter键添加它。当我按下时,例如 X 我想离开"添加成员"处理并转到下一步,例如,"添加会议标题"。
如何将成员添加到我的阵列?我输入姓名时如何进入下一步?这段代码不起作用:
Console.Write("Enter members here: ");
memberList = Console.ReadLine();
string[] memberList;
答案 0 :(得分:5)
You'll need to use a conditional loop to accomplish this, a while
loop would work pretty good.
Also, using a List<string>
would be better in this scenario since you (i) need to add things to it, and (ii) you don't know how big to make the array when you first declare it since you don't know how many names the user will enter.
Something like:
var names = new List<string>();
var input = Console.ReadLine();
while (input.ToUpper() != "X")
{
names.Add(input);
input = Console.ReadLine();
}
foreach (var name in names)
{
Console.WriteLine(name);
}
If you're wanting to move to the next step immediately after an user presses X (without them having to press Enter), you can look into using Console.ReadKey
but it'd be more complicated since you'd have to collect one character at a time to get the name and check if they key pressed is Enter, in which case you'd move on to the next name. There's also the complexity of known when a "X" is just part of someone's name, e.g. Xavier, or whether meant to move on to the next step.
答案 1 :(得分:2)
假设用户键入以下内容:“Jake,Julia,Craig”
string[] memberlist = Console.ReadLine().Split(',');
最后你需要在逗号后面的空格的每个名称原因上使用.Trim()。
编辑:对于“多线”解决方案,请查看@Jeff Bridgman帖子。