我没有发现什么可以回答这个问题,我认为这对于我的代码来说是不同的。可能是因为我向数组中添加了一个自定义对象,但我仍然不知道是什么原因造成了这种情况。错误出现在第35行。代码附在下面。
using System;
class Player {
public string abilitySet;
public string name;
public void useAbility() {
if (abilitySet == "fire") {
Console.WriteLine(name + " used fireball which did 40 damage!");
}
}
}
class Match {
public int PlayerCount;
public Player[] players;
public void Start() {
Console.WriteLine("Game started! There are " + PlayerCount + " players!");
}
}
class Program {
public static void Main(string[] args) {
Match match = new Match();
Console.WriteLine("How many players are there?");
string playerCount = Console.ReadLine();
if (Int32.TryParse(playerCount, out int j)) {
Console.WriteLine("You have selected " + playerCount + " players!");
match.PlayerCount = j;
for (int i = 0; i < j; i++) {
Player plr = new Player();
match.players[i] = plr;
plr.name = "Player " + i;
Console.WriteLine("What do you want " + plr.name + "'s ability set to be?");
string ability = Console.ReadLine();
if (ability.ToLower() == "fire") {
Console.WriteLine(plr.name + " has " + ability + "!");
} else {
Console.WriteLine("That is not a ability!");
}
}
} else {
Console.WriteLine("Please enter a number of players not text!");
}
}
}发布于 2022-01-09 06:36:15
正如@Backs所提到的,您没有初始化变量。但是我会按照下面的方式组织您的代码,并使用一个列表而不是一个数组。读起来容易多了,你不觉得吗?
using System;
class Player
{
public Player(string name)
{
Name = name;
}
public string Name { get; set; } = String.Empty;
public string AbilitySet { get; set; } = String.Empty;
public void UseAbility()
{
if (AbilitySet == "fire")
{
Console.WriteLine(Name + " used fireball which did 40 damage!");
}
}
}
class Match
{
public List<Player> Players { get; set; } = new List<Player>();
public void Start()
{
Console.WriteLine("Game started! There are " + Players.Count + " players!");
}
}
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("How many players are there? Or type Q+ENTER to quit.");
int numberOfPlayers = 0;
while (true)
{
string input = Console.ReadLine();
if (input == "Q")
{
System.Environment.Exit(1);
}
if (!Int32.TryParse(input, out numberOfPlayers))
{
Console.WriteLine("Invalid input. Please enter a numeric value.");
continue;
}
if (numberOfPlayers <= 0)
{
Console.WriteLine("Number of players must be at least 1.");
continue;
}
break;
}
Match match = new Match();
for (int i = 0; i < numberOfPlayers; i++)
{
match.Players.Add(new Player($"Player {i + 1}"));
}
match.Start();
}
}发布于 2022-01-09 06:05:00
未初始化Match类的字段Match。您应该创建一个数组:
match.players = new Player[j];或者在构造函数中这样做:
class Match {
public int PlayerCount;
public Player[] players;
public Match(int count) {
PlayerCount = count;
players = new Player[count];
}
public void Start() {
Console.WriteLine("Game started! There are " + PlayerCount + " players!");
}
}
Match match = new Match(j);https://stackoverflow.com/questions/70638818
复制相似问题