索引返回错误的值

时间:2014-12-01 00:16:18

标签: c#

我创建了一个玩家类,并为我的菜单驱动的玩家系统制作了一个数组,我试图创建一个玩家。我的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;
    }

1 个答案:

答案 0 :(得分:0)

GetInsertIndex()将始终返回0或更高,这意味着对(playerindex != -1)的检查将始终评估为true