任何人都可以帮我解决问题吗?
struct Player
{
public string Name;
public int X;
public int Y;
}
static Player[] players = new Player[amountofPlayers];
static void ResetGame() {
Console.WriteLine("Welcome to the game!");
Console.Write("How many player will be taking part today: ");
string playerNo = Console.ReadLine();
amountofPlayers = int.Parse(playerNo);
if (amountofPlayers <= 4)
{
for (int i = 0; i < amountofPlayers; i = i + 1)
{
int displayNumber = i + 1;
Console.Write("Please enter the name of player " + displayNumber + ": ");
players[i].Name = Console.ReadLine(); //error is here
}
}
else
{
Console.WriteLine("Please enter a number of players less than 4!");
}
}
static int amountofPlayers;
答案 0 :(得分:6)
这一行:
static Player[] players = new Player[amountofPlayers];
在根据用户输入为amountOfPlayers
分配值之前,正在执行。因此amountOfPlayers
的默认值为0,您将创建一个包含0个元素的数组。
我建议您只声明变量:
static Player[] players;
然后在amountOfPlayers
方法中使ResetGame
成为本地变量,在您询问有多少玩家后初始化数组:
static void ResetGame() {
Console.WriteLine("Welcome to the game!");
Console.Write("How many player will be taking part today: ");
string playerNo = Console.ReadLine();
int amountofPlayers = int.Parse(playerNo);
players = new Player[amountOfPlayers];
...
}
我&#39; 还建议将Player
作为一个类而不是一个结构,保持字段为私有,并改为使用属性。
答案 1 :(得分:2)
你的玩家阵列被初始化为0,因为它是静态的,起初你的numberofPlayers
是0.当你获得玩家数量时,你必须初始化它。
static Player[] players;
static int amountofPlayers;
static void ResetGame()
{
Console.WriteLine("Welcome to the game!");
Console.Write("How many player will be taking part today: ");
string playerNo = Console.ReadLine();
amountofPlayers = int.Parse(playerNo);
if (amountofPlayers <= 4)
{
players = new Player[amountofPlayers];
for (int i = 0; i < amountofPlayers; i = i + 1)
{
int displayNumber = i + 1;
Console.Write("Please enter the name of player " + displayNumber + ": ");
players[i].Name = Console.ReadLine(); //error is here
}
}
else
{
Console.WriteLine("Please enter a number of players less than 4!");
}
}
答案 2 :(得分:2)
struct Player
{
public string Name;
public int X;
public int Y;
}
static Player[] players = new Player[amountofPlayers];
static void ResetGame() {
Console.WriteLine("Welcome to the game!");
Console.Write("How many player will be taking part today: ");
string playerNo = Console.ReadLine();
amountofPlayers = int.Parse(playerNo);
Array.Resize(ref players, amountofPlayers ); /// this will resize your array element to the accepted amount of player
if (amountofPlayers <= 4)
{
for (int i = 0; i < amountofPlayers; i = i + 1)
{
int displayNumber = i + 1;
Console.Write("Please enter the name of player " + displayNumber + ": ");
players[i].Name = Console.ReadLine(); //error is here
}
}
else
{
Console.WriteLine("Please enter a number of players less than 4!");
}
}
static int amountofPlayers;
答案 3 :(得分:2)
players
在设置amountofPlayers
之前初始化(即当amountofPlayers
仍然为零时)
看到您只想允许最多4个玩家设置,您可能需要将amountofPlayers
初始化为4:
static int amountofPlayers = 4;