如何接受来自用户的数据并将其存储在C#中的列表中 [英] How to accept data from user and store it in a list in C#
问题描述
我正在尝试从用户那里获取输入并将其存储在列表中。
程序没有将user1返回到最后一句,而是显示data。要改变什么,它会显示user1?
我尝试过:
使用System;
使用System.Collections.Generic;
公共类数据
{
public string userName;
public void inputData()
{
Console.WriteLine(Inside data class);
Console.WriteLine(输入用户名);
userName = Console.ReadLine();
Console.WriteLine(你输入了{0},用户名);
}
}
公共类mainClass
{
public static void Main (string [] args)
{
Console.WriteLine(Inside Main);
data d = new data();
d.inputData();
Console.WriteLine(将用户名存储到列表......);
列出 newList = new List ();
newList.Add(d);
foreach(新列表中的var s)
{
Console.WriteLine (存储的用户名是\{0} \,s);
}
}
}
***************************输出***************** ***********************
内部主要
内部数据类
输入用户名
user1
您输入的用户1
将用户名存储到列表中。 。 。 。
存储的用户名是data
I am trying to take input from user and store it in a list.
Program is not returning "user1" to last sentence, instead it displays "data". What to change so it will display "user1"?
What I have tried:
using System;
using System.Collections.Generic;
public class data
{
public string userName;
public void inputData()
{
Console.WriteLine("Inside data class");
Console.WriteLine("Enter username");
userName = Console.ReadLine();
Console.WriteLine("you entered {0}",userName);
}
}
public class mainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Inside Main");
data d = new data();
d.inputData();
Console.WriteLine("Storing user name to list . . . .");
List newList = new List();
newList.Add(d);
foreach ( var s in newList)
{
Console.WriteLine("stored user name is \"{0}\"", s);
}
}
}
***************************OUTPUT****************************************
Inside Main
Inside data class
Enter username
user1
you entered user1
Storing user name to list . . . .
stored user name is "data"
推荐答案
如果你想提示用户用户列表,你必须使用循环。例如 - 在伪代码中:
If you would like to prompt user for a list of users, you have to use loop. For example - in pseudo-code:
create empty *list* //list of strings
create *username* //string variable
display "Enter user names as many you wish... "Accept empty line to finish" //empty line = escapeCharacter for do-while loop
create *counter* //int variable
do
display Format("Enter {0} name:", *counter*)
get *username*
add *username* to list
increase *counter* //counter+=1
while (escapeCharacter is meet)
foreach (*usr* in *list*)
display *usr*
next
这就是全部!
That's all!
Console.WriteLine("stored user name is \"{0}\"", s.userName);
这篇关于如何接受来自用户的数据并将其存储在C#中的列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!