所以当我的答案在TextValidation上是错误的时 例如,TextValidation值=“寓言”将不起作用,并且当TextValidation值不在“寓言”中或其他任何情况下均不会发生。我试图删除语句上的else,并且TextValidation value =“ fable”再次起作用。我不知道我的代码T_T有什么问题。
public TextMeshProUGUI TextValidation;
string[] rightanswers = { "able", "alef", "bale", "blae", "feal",
"flab", "flea", "leaf", "fable" };
public void rightanswersButton()
{
for (int index = 0; index < rightanswers.Length; index++)
{
if (finalAnswer == rightanswers[index])
{
TextValidation.text = "You are correct your answer is :" + finalAnswer;
delete();
}
else
{
TextValidation.text = "You are wrong";
delete();
}
}
}
答案 0 :(得分:2)
您只关心数组中是否存在用户的值,但是您正在检查每个值,因此最终将找到最多一个正确的答案和一堆错误的答案,然后打印淘汰了大量不必要的消息。
有几种方法可以解决这个问题。例如,如果找到一个值,则可以设置一个标志并尽早退出循环。
bool isFound = false;
for (int index = 0; index < rightanswers.Length; index++)
{
if (finalAnswer == rightanswers[index])
{
isFound = true;
break;
}
}
if (isFound)
TextValidation.text = "You are correct your answer is :" + finalAnswer;
else
TextValidation.text = "You are wrong";
delete();
或者,您可以使用LINQ来查找数组中的任何元素是否与您要查找的值匹配。
if (rightanswers.Any(x => x == finalAnswer))
TextValidation.text = "You are correct your answer is :" + finalAnswer;
else
TextValidation.text = "You are wrong";
delete();