我正在尝试从另一个类调用一个方法。当我选择此菜单选项时,p.players()
应该会打开:
static void Main(string[] args)
{
Enumfactory.Position choice;
Enumfactory.Location location;
Player p = new Player();
Console.WriteLine("Please choose from one of the following:");
Console.WriteLine("1. GoalKeeper");
Console.WriteLine("2. Defender");
Console.WriteLine("3. Midfielder");
Console.WriteLine("4. Striker");
choice = ((Enumfactory.Position)(int.Parse(Console.ReadLine())));
string exit = "";
while (exit != "Y")
{
switch (choice)
{
case Enumfactory.Position.GoalKeeper:
//assigning the actual position
p.Position = Enumfactory.Position.GoalKeeper;
p.players();
break;
以下是来自Player类的方法:
public string[] players()
{
List<string> PlayerList = new List<string>();
Player player = new Player();
string enterplayer = "";
while (enterplayer == "Y")
{
Console.WriteLine("Please enter the teamnumber of your player");
player.teamNumber = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the name of your player");
player.name = Console.ReadLine();
Console.WriteLine("Please enter the surname of your player");
player.surname = Console.ReadLine();
Console.WriteLine("Enter the age of your player");
player.age = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter the goals the player scored");
player.goalsScored = int.Parse(Console.ReadLine());
PlayerList.Add(player.teamNumber.ToString());
PlayerList.Add(player.name);
PlayerList.Add(player.surname);
PlayerList.Add(player.age.ToString());
PlayerList.Add(player.goalsScored.ToString());
Console.WriteLine("Do you wish to enter another player? Y/N");
enterplayer = Console.ReadLine();
}
foreach (var item in PlayerList)
{
Console.WriteLine("to view your player");
Console.Write("{0}", item);
}
Console.ReadKey();
return player.players();
}
答案 0 :(得分:1)
该方法可能正在被调用,它只是你的while循环永远不会运行。这是因为enterplayer
永远不会等于&#34; Y&#34;因此,你的while循环中的代码将永远不会运行(这使得它看起来像你的方法没有被调用)。
您的意思是以下吗?
string enterplayer = "";
while (enterplayer != "Y")
{
...
}
答案 1 :(得分:0)
您编写它的方式中的while
循环将在第一次进入循环之前评估条件。您将enterplayer
初始化为""
,因此第一次测试while条件时它会返回false
并且永远不会进入循环。您可以通过两种方式解决此问题,方法是初始化enterplayer
,以便第一次满足条件:
string enterplayer = "Y";
while (enterplayer == "Y") // We set enterplayer to "Y" so this is true first time through
{
// Your code to add a player goes here
}
...或者,您可以使用稍微不同的while
循环形式,最后评估条件。这意味着循环中的代码总是至少执行一次,然后只要满足最后while
条件就重复:
string enterplayer = "";
do // This always enters the loop code first time
{
// Your code to add a player goes here
}
while (enterplayer == "Y")
由于您的代码使用enterplayer
变量决定是否添加更多玩家,我更喜欢第二种形式,即使作为while
构造的变体,它可能不如前者。