如何根据用户输入在一行上声明多个if语句?

时间:2015-06-12 00:20:21

标签: c# if-statement

if (userInput == "hello") ***or*** (userInput == "bye")
{
    Console.WriteLine("So, which one is it?");
}

在上下文中,我希望用户在一行中使用两个if语句输入两个含义相同的决定。

3 个答案:

答案 0 :(得分:0)

有几种方法可以实现这一目标。也许最简单的就是使用||运算符:

if (userInput == "hello" || userInput == "bye")
{
    Console.WriteLine("So, which one is it?");
}

如果列表较长,您可以创建一个列表,并查找匹配项:

var responses = new List<string> {
    "hello", "bye"
};
if (responses.Contains(userInput)) {
    Console.WriteLine("So, which one is it?");
}

另一个解决方案是使用switch语句:

switch (userInput) {
    case "hello":
    case "bye":
        ...
        break;
    case "go-away":
    case "come-back":
        ...
        break;
}

答案 1 :(得分:0)

这很简单:

if (userInput == "hello" || userInput == "bye") // This line had changed
{
    Console.WriteLine("So, which one is it?");
}

答案 2 :(得分:0)

您可以为OR执行此操作:

if (userInput == "hello" || userInput == "bye")
{
    Console.WriteLine("So, which one is it?");
}

或者如果你想要真正的

if (userInput == "hello" && userInput == "bye")
{
    Console.WriteLine("So, which one is it?");
}