[英]How can i make a proper if/else if/else statement?
我正在尝试使用 c# 在 Unity 中为我的游戏开发 class 创建一个游戏。 我在尝试进行输入语句时遇到问题。 我希望它做的是,如果我输入例如“1”,我希望它(现在)响应“你选择了 1”。 但它不是在播放它。 如果有帮助,我会在我的游戏中使用它。
这是我到目前为止所拥有的
void UserInput(string input)
{
if (input == "1")
{
print("You choose 1");
}
else if (input == "2")
{
print("You choose 2");
}
else
{
print("Invalid Response");
}
}
任何帮助都会很棒! 谢谢!
编辑:谢谢大家帮助我。 我对这一切都很陌生。 我感谢所有的回应
如果您的 output 输入了什么,也许您可以发现问题:
void UserInput(string input)
{
Console.WriteLine($"The input was '{input}'");
当输入为空时,单引号很有用,因为这样您将看到The input was ''
而不是The input was
。
在您的特定情况下,您似乎只想告知最终用户他们的输入,在这种情况下您可以简单地执行以下操作:
public void UserInput(string input) {
Console.WriteLine($"You choose {input}");
}
但是,如果您只想处理某些情况(在您的情况下,只有 1 和 2),那么您可以使用 switch 语句:
public void UserInput(string input) {
switch(input) {
case "1":
case "2":
Console.WriteLine($"You choose {input}"); // will only write 1 or 2
break; // necessary to prevent fall-through
default:
Console.WriteLine("Invalid Response");
另一种解决方案是
void UserInput(string input)
{
if (string.IsNullOrEmpty(input))
{
Console.WriteLine("Invalid Response");
return;
}
Console.WriteLine($"You choose {input}");
}
void UserInput(string input){
default:
Console.WriteLine("Invalid Input"); break;
case "1":
Console.WriteLine("You haven chose 1"); break;
case "2":
Console.WriteLine("You have chosen 2"); break;
}
Console.Write("Input: ");
var Input = Console.ReadLine();
UserInput(Input);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.