我有这个代码的麻烦,我想拥有的代码返回一个答案,如果输入列表中的项目相匹配,(不能使用数组),或者如果没有匹配,写行一次,重复代码,但是当我这样做时,结果是:
Please enter the type of gem you want on your wedding ring:
diamond
Im sorry that was not a valid selection.
Im sorry that was not a valid selection.
Im sorry that was not a valid selection.
Your wedding ring will feature your selection: diamond
Im sorry that was not a valid selection.
Im sorry that was not a valid selection.
Run Code Online (Sandbox Code Playgroud)
代码是;
List<string> Gems = new List<string>();
Gems.Add("ruby");
Gems.Add("emerald");
Gems.Add("topaz");
Gems.Add("diamond");
Gems.Add("pearl");
Gems.Add("infinity stone");
Console.WriteLine("Please enter the type of gem you want on your wedding ring: ");
string want = Console.ReadLine();
for (int g = 0; g < Gems.Count; g++)
{
if (want == Gems[g])
{
Console.WriteLine("Your wedding ring will feature your selection: " + Gems[g]);
}
else
{
Console.WriteLine("Im sorry that was not a valid selection.");
}
}
Run Code Online (Sandbox Code Playgroud)
want
您可以使用List<T>
类型上的一个有用方法,而不是循环遍历列表,尝试查找它是否包含手动值,例如List.Contains
:
string want = Console.ReadLine();
if (Gems.Contains(want))
{
Console.WriteLine("Your wedding ring will feature your selection: " + want);
}
else
{
Console.WriteLine("Im sorry that was not a valid selection.");
}
Run Code Online (Sandbox Code Playgroud)