So I want to store the following data to 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());
Currently I have this and the problem is it only saves the first set of data I input.
while (users[i] != null)
{
i++;
}
users[i] = new DB(name);
users[i].SaveData(name, age, gender);
where
public void SaveData(string a, int b, string c)
{
name = a;
age = b;
gender = c;
}
You have to input data in for loop, like that:
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);
}
Update 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);
}
}
A solution using For loop (as suggested by AlphaDelta in the comments) and your specific situation could be:
for (int i = 0; i < users.Length; i++)
{
if (users[i] == null)
{
users[i] = new DB(name);
users[i].SaveData(name, age, gender);
break;
}
}
This basically iterates your users array looking for the next null
, and if found, it will save a user there, break
means it stops the loop immediately.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.