好的,有几件事:
你UserClass的是一个array. 它将保存项目,但除非您附加到它,否则您不能将用户输入写入它。这是Arrays来自 MSDN 的 C# 参考。
您正在使用.Contains()astring array而不是 a string。虽然从逻辑上讲,是的,但string array 确实包含这些值。虽然,如果它真的运行/编译,所有的if statements都会运行真实而不是从用户输入中选择。
这让我想到了我的下一件事——你要求但从未在如图所示的方法中user input真正允许它。Main()最常见的方式(我见过)是这样的:
string input = Console.ReadLine();
哪个,我看到您正在尝试实施,所以这不是问题:)
此代码应该适用于(我将分解我的更改):
static void Main(string[] args)
{
string userName = "James";
string[] userClass = new string[3] { "mage", "warrior", "assassin" };
Console.WriteLine("What class will you be? You can choose from Mage, Warrior or Assassin:");
string input = Console.ReadLine();
if (input.ToLower() == userClass[0])
{
string Message = "You are a strong Willed Mage " + userName;
Console.WriteLine(Message);
}
else if (input.ToLower() == userClass[1])
{
string Message = "Your are a valiant Warrior " + userName;
Console.WriteLine(Message);
}
else if (input.ToLower() == userClass[2])
{
string Message = "You are a vigilant Assassin " + userName;
Console.WriteLine(Message);
}
else
Console.WriteLine("No proper class selected...");
Console.ReadLine();
}
string userName与您的保持相同string[] userClass(我已将大写更改为驼峰式)。只要您正确检查,将这些userClasss 存储在 a中就没有问题(我认为)。arrayarray
Instead of checking if the string[] userClass array contains these items, because we know it does as we've written it and as stated before, it would always run true. Instead, we check to see if the user input matches something within the array.
I have created string input = Console.ReadLine() to allow for user input, and then I check input against the string[] userClass values. I have added .ToLower() and changed the array values to all lower case. This way, if a user inputs mAgE instead of Mage , there will not be an error thrown.
Another way to go about it, if you are wanting to avoid using an array , is to use a switch:
switch (input.ToLower())
{
case "mage":
Console.WriteLine($"You are a strong Willed Mage {userName}");
//assign user class
break;
case "warrior":
Console.WriteLine($"Your are a valiant Warrior {userName}");
//assign user class
break;
case "assassin":
Console.WriteLine($"You are a vigilant Assasin {userName}");
//assign user class
break;
}