int PlayerAmount = 10;
int CurrentPlayer = 0;
Player[] player = new Player[PlayerAmount];
while (true)
{
string Input;
Console.WriteLine("What would you like to do?");
Console.WriteLine("1. Create new player and score.");
Console.WriteLine("2. Display Highscores.");
Console.WriteLine("3. Write out to XML file.");
Console.Write("Input Number: ");
Input = Console.ReadLine();
if (Input == "1")
{
if (CurrentPlayer >= PlayerAmount)
{
Console.WriteLine();
Console.WriteLine("MAX AMOUNT OF PLAYERS HAS BEEN REACHED!");
Console.WriteLine();
}
else
{
string PlayerName;
string Score;
Console.WriteLine();
Console.WriteLine("-=CREATE NEW PLAYER=-");
Console.Write("Player name: ");
PlayerName = Console.ReadLine();
Console.Write("Player score: ");
Score = Console.ReadLine();
//=========================================
//THIS IS WHERE THE ERROR OCCURS===========
//=========================================
player[CurrentPlayer].Name = PlayerName;
Console.WriteLine("Player \"" + player[CurrentPlayer].Name + "\" with the score of \"" + player[CurrentPlayer].Score + "\" has been created successfully!" );
Console.WriteLine();
}
}
else if (Input == "2")
{
Console.WriteLine("Displaying the highscores");
}
else if (Input == "3")
{
Console.WriteLine("Writing to XML file");
}
else
{
Console.WriteLine("INVALID INPUT");
}
}
我已经尝试过使用字符串副本,但这只是给了我同样的错误,我已经在代码中指出了问题,但是如果你看不到它正在复制播放器名称的位置: “player [CurrentPlayer] .Name = PlayerName;”
提前致谢
答案 0 :(得分:1)
在我看来:
player[CurrentPlayer].Name
为空。确保索引currentPlayer
处的播放器对象不为空。
初始化数组时,默认情况下所有对象都为空(非基元)。所以你必须在数组中为每个索引实例化每个玩家。
这一行:
Player[] player = new Player[PlayerAmount];
仅分配一个大小为playerAmount
的数组(在您的情况下为10);
你需要这个来初始化它们:
for(int i =0; i < player.length;i++)
{
player[i] = new Player();
}
答案 1 :(得分:1)
您没有初始化Player
数组的每个成员。做完之后:
Player[] player = new Player[PlayerAmount];
您可能也希望这样做:
for (int i = 0; i < PlayerAmount; i++)
{
Player[i] = new Player();
}
因为事先,数组只包含一堆null
引用。
答案 2 :(得分:0)
你也可以像
一样做懒惰的事情player[CurrentPlayer] = new Player();
player[CurrentPlayer].Name = PlayerName;