返回错误值的索引
本文关键字:索引 错误 返回 | 更新日期: 2023-09-27 18:32:45
我创建了一个播放器类,并从该类为我的菜单驱动的播放器系统制作了一个数组,我正在尝试创建一个播放器。我的 ProcessCreate 方法假设检查从 InsertPlayer 返回的插入索引,如果它不等于 -1,但由于某种原因它没有从插入播放器返回插入索引为 -1,则显示"已成功创建"消息。我不确定如何解决这个问题,并且提前对长代码感到抱歉,但我认为这一切都可能与找出问题有关。
任何帮助将不胜感激
这是我的 ProcessCreate 方法检查插入播放器的部分
playerindex = InsertPlayer(number, firstName, lastName, goals, assists, players, ref playerCount);
if (playerindex != -1)
{
{
Console.WriteLine("'n{0,7} {1,-20}{2, -20}{3,8}{4,8}{5,8}'n", "Number", "First Name", "Last Name", "Goals", " Assists", "Points");
Console.WriteLine("{0,7} {1,-20}{2, -20}{3,8}{4,8}{5,8}",
players[playerindex].Number, players[playerindex].FirstName, players[playerindex].LastName,
players[playerindex].Goals, players[playerindex].Assists, players[playerindex].Points());
Console.WriteLine("Sucessfully created!");
Console.WriteLine();
}
}
}
else
Console.WriteLine("'nCreate Player: the player number already exists");
}
else
Console.WriteLine("'nCreate Player: the player roster is already full");
}
这是我的 InsertPlayer 和 GetInsertIndex 方法
static Int32 InsertPlayer(Int32 number, String firstName, String lastName, Int32 goals,
Int32 assists, Player[] players, ref Int32 playerCount)
{
Int32 insertIndex, shiftCount;
insertIndex = GetInsertIndex(number, players,ref playerCount);
for (shiftCount = playerCount; shiftCount > insertIndex; shiftCount--)
players[shiftCount] = players[shiftCount - 1];
try
{
players[insertIndex] = new Player(number, firstName, lastName, goals, assists);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
playerCount++;
return insertIndex;
}
static Int32 GetInsertIndex(Int32 playernumber,Player[] players,
ref Int32 playerCount)
{
Int32 index = 0;
bool found = false;
while (index < playerCount && found == false)
if (players[index].Number > playernumber)
found = true;
else
index++;
return index;
}
GetInsertIndex()
将始终返回 0 或更大,这意味着您对(playerindex != -1)
的检查将始终计算为 true
。