所以我想将以下数据存储到users = new DB[10];
Console.WriteLine("=====REGISTER=====");
Console.Write("What is your name? ");
name = (Console.ReadLine());
Console.Write("How old are you? ");
age = (int.Parse(Console.ReadLine()));
Console.Write("What is your gender? M for Male, F for Female");
gender = (Console.ReadLine());
目前我有这个,问题是它只保存我输入的第一组数据。
while (users[i] != null)
{
i++;
}
users[i] = new DB(name);
users[i].SaveData(name, age, gender);
其中
public void SaveData(string a, int b, string c)
{
name = a;
age = b;
gender = c;
}
答案 0 :(得分:0)
你必须在for循环中输入数据,如:
Console.WriteLine ("=====REGISTER=====");
var users = new DB[10];
for (int i = 0; i < users.Length; i++)
{
//input data
Console.Write ("What is your name? ");
name = (Console.ReadLine ());
Console.Write ("How old are you? ");
age = (int.Parse (Console.ReadLine ()));
Console.Write ("What is your gender? M for Male, F for Female");
gender = (Console.ReadLine ());
// store data
users[i] = new DB (name);
users[i].SaveData (name, age, gender);
}
更新1:
static DB[] users = new DB[10];
static void Main (string[] args)
{
//user 1
Registration ();
//user 2
Registration ();
}
private static void Registration ()
{
Console.WriteLine ("=====REGISTER=====");
Console.Write ("What is your name? ");
name = (Console.ReadLine ());
Console.Write ("How old are you? ");
age = (int.Parse (Console.ReadLine ()));
Console.Write ("What is your gender? M for Male, F for Female");
gender = (Console.ReadLine ());
int i = 0;
while (users.Length > i && users[i] != null)
{
i++;
}
if (users.Length > i)
{
users[i] = new DB ();
users[i].SaveData (name, age, gender);
}
}
答案 1 :(得分:0)
使用For循环的解决方案(在评论中由AlphaDelta建议)和您的具体情况可能是:
for (int i = 0; i < users.Length; i++)
{
if (users[i] == null)
{
users[i] = new DB(name);
users[i].SaveData(name, age, gender);
break;
}
}
这基本上会迭代你的用户数组,寻找下一个null
,如果找到,它会在那里保存用户,break
表示它会立即停止循环。