如何解决C#System.IndexOutOfRangeException-我的代码起作用了,但随后又发生了变化-可能是由于类的调整-新手询问
新手在这里:
我正在开发一个小型的主机游戏。几天前,我想出了一些代码,这些代码完全可以完成我在字符创建过程中想要的工作-我希望用户可以在名称字符串中包含数字或为空的情况下键入任何内容,然后强迫他们重试。如果名称是普通字符串,则我将第一个字母替换为大写字母,以便稍后使用。
我想到了这样的东西:
Player player = new Player();
do
{
char x; char y;
Console.Write("Enter your name: ");
player.playerName = Console.ReadLine().ToLower();
x = player.playerName[0]; y = Convert.ToChar(player.playerName[0].ToString().ToUpper());
player.playerName = player.playerName.Replace(x,y).ToString();
}
while (player.playerName == "" || !(player.playerName).All(char.IsLetter));
几天来,它一直运行良好,就像其他事情一样,我让我的朋友尝试“打破”游戏,但他没有设法做到。我继续编写代码,做其他事情。
昨天我正在从事其他工作,因此我不得不在网站上How to call a method after each line of code or something like that上提问。 我得到了一个很好的答案,并且使用了它,一切正常。但是,因此,我不得不在Player()类中进行一些更改。基本上,现在看起来像这样:
public class Player
{
public static bool isDead;
public string playerName;
public string playerSex;
public string playerVocation;
public string playerRace;
public int playerLevel;
public int playerExperience;
protected int _playerHealth = 0;
public int playerHealth
{
set
{
_playerHealth = value;
if (_playerHealth == 0)
{
isDead = true;
Console.WriteLine("You are dead!");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.Write("Press any key to continue...");
Console.ReadKey();
Console.Clear();
Environment.Exit(0);
}
}
get
{
return _playerHealth;
}
}
public int playerMana;
public int playerMagicResistance;
public int playerPhysicalResistance;
}
现在,当我在创建字符名称时按Enter键时,主“程序”中的行:x = player.playerName[0]
会引发错误。在进行更改之前,我要说的是用户输入为“空”时,它只会要求他们再次输入。现在,它仅引发IndexOutOfRange
错误。
我尝试在Player()
类中使变量成为静态变量,然后删除static关键字并仅声明一个新的player对象-现在似乎没有任何效果,尽管尝试了,但我没有找到解决方案。以前它一直在起作用,现在却没有起作用,这真使我丧命。
#edit 我读了建议的答案,但这主要是关于数组的,并非如此。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。