而声明忽略响应值

时间:2012-07-25 13:17:09

标签: c# command-line if-statement while-loop console-application

我有一个命令行要求用户说(Y / N),并将此值传递给checkResponse方法。

由于某种原因,while循环忽略该值,即使我调试它时显示的值为“Y”。当值设置为“N”时,它也会继续循环。如果我将if语句移动到while语句下面,程序就会中途运行。我可以发送一个初始值“Y”,而while语句将忽略它并开始在其中运行代码。

知道我缺少什么或过度看?

提前致谢。

public void checkResponse(string response, string confirmValue)
{
    Console.WriteLine(response);
    Console.WriteLine(response);
    if (response == "Y")
    {
        return;
    }
    else if (response == "N")
    {
        Environment.Exit(0);
    }
    else
    {
        while ((response != "Y") || (response != "N"))
        {
            Console.Clear();
            Console.WriteLine("\"" + response + "\" is not a valid response.");
            Console.WriteLine();
            Console.WriteLine("You entered:" + confirmValue);
            Console.WriteLine("Is this correct? (Y/N)");
            response = Console.ReadLine().ToUpper();
        }
    }
}

5 个答案:

答案 0 :(得分:11)

OR更改为AND逻辑运算符:

(response != "Y") && (response != "N")

答案 1 :(得分:4)

((response != "Y") || (response != "N"))始终为true

答案 2 :(得分:3)

while ((response != "Y") || (response != "N"))

永远是真的,因为响应不能同时是Y和N.

答案 3 :(得分:0)

确定。如果while循环终止怎么办?我们希望它再次检查:

public void checkResponse(string response, string confirmValue)
{
Check:
    Console.WriteLine(response);
    Console.WriteLine(response);
    if (response == "Y")
    {
        return;
    }
    else if (response == "N")
    {
        Environment.Exit(0);
    }
    else
    {
        while ((response != "Y") && (response != "N"))
        {
            Console.Clear();
            Console.WriteLine("\"" + response + "\" is not a valid response.");
            Console.WriteLine();
            Console.WriteLine("You entered:" + confirmValue);
            Console.WriteLine("Is this correct? (Y/N)");
            response = Console.ReadLine().ToUpper();
        }
        goto Check;
    }
}

或者,更好:

public void checkResponse(string response, string confirmValue)
{
    Console.WriteLine(response);
    while (response != "Y" && response != "N")
    {
            Console.Clear();
            Console.WriteLine("\"" + response + "\" is not a valid response.");
            Console.WriteLine();
            Console.WriteLine("You entered:" + confirmValue);
            Console.WriteLine("Is this correct? (Y/N)");
            response = Console.ReadLine().ToUpper();
    }
    if (response == "N")
           Environment.Exit(0);
}

答案 4 :(得分:0)

你确定输入也是大写的吗?您可以使用equals方法并忽略大小写。

message.Equals("Y", StringComparison.InvariantCultureIgnoreCase);

编辑:虽然这可能更好地用于或代替一个错误,并且是您的实际问题。