1
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");
    }
}

我已经尝试使用字符串复制,但这只是给了我同样的错误,我已经在代码中指出了问题,但是如果你看不到它是复制玩家名称的位置:“玩家 [ CurrentPlayer].Name = PlayerName;"

提前致谢

4

3 回答 3

1

在我看来:

player[CurrentPlayer].Name

一片空白。确保索引处的播放器对象currentPlayer不为空。

初始化数组时,所有对象默认为空(非基元)。因此,您必须根据数组中的索引实例化每个玩家。

这一行:

Player[] player = new Player[PlayerAmount];

仅分配一个大小数组playerAmount(在您的情况下为 10);

你需要这个来初始化它们:

for(int i =0; i < player.length;i++)  
{  
     player[i] = new Player();
}  
于 2012-12-26T22:33:30.183 回答
1

您不会初始化Player数组的每个成员。做完之后:

Player[] player = new Player[PlayerAmount];

您可能也想这样做:

for (int i = 0; i < PlayerAmount; i++)
{
    Player[i] = new Player();
}

因为事先,数组只包含一堆null引用。

于 2012-12-26T22:36:34.993 回答
0

您也可以制作类似懒惰的东西

player[CurrentPlayer] = new Player();
player[CurrentPlayer].Name = PlayerName;
于 2012-12-27T00:09:02.347 回答