我大约有一周的时间学习 C# 并且具有 0 的先验编码知识。有人可以告诉我为什么这不起作用吗?
string[] afirmatives = {"Yes", "yes", "YES", "Yeah", "yeah", "YEAH",
"Yep", "yep", "YEP", "Yup", "yup", "YUP", "Y", "y" };
/*string afirmatives = "Yes";*/
Console.Write("Are you a Human? ");
string humanAnswer = Console.ReadLine();
string answer = (humanAnswer = afirmatives) ?
"That sounds like something a robot would say."
: "Invalid Input";
Console.WriteLine(answer);
Console.ReadLine();
我知道我可以让它只使用一个字符串值,但是我需要做什么不同的事情来使用多个?
我是否必须创建多个 if else 行?
谢谢!
编辑
Xareth 帮助我找到了答案。我需要添加一个“包含”的东西或其他东西。这是新的操作代码。
string[] afirmatives = {"Yes", "yes", "YES", "Yeah", "yeah", "YEAH",
"Yep", "yep", "YEP", "Yup", "yup", "YUP", "Y", "y" };
Console.Write("Are you a Human? ");
string humanAnswer = Console.ReadLine();
string answer = humanAnswer = afirmatives.Contains(humanAnswer)
? "That's something a robot would say."
: "Invalid Input";
Console.WriteLine(answer);
Console.ReadLine();
尝试:
using System.Linq;
string[] afirmatives = {"Yes", "yes", "YES", "Yeah", "yeah", "YEAH",
"Yep", "yep", "YEP", "Yup", "yup", "YUP", "Y", "y" };
/*string afirmatives = "Yes";*/
Console.Write("Are you a Human? ");
string humanAnswer = Console.ReadLine();
string answer = (afirmatives.Contains(humanAnswer)) ?
"That sounds like something a robot would say."
: "Invalid Input";
Console.WriteLine(answer);
Console.ReadLine();
using System.Linq;
顶部通知
humanAnswer = afirmatives
不起作用的原因是因为=
是赋值运算符。通过使用它,您试图humanAnswer
从afirmatives
.
要比较字符串,您应该使用相等运算符。因此,string afirmatives = "Yes";
在以下情况下有效的情况下humanAnswer == afirmatives
。
但是,您正在与humanAnswer
数组进行比较,因此使用 Linq 是一种测试数组或列表是否包含值的简单方法
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句