如何使用if / else语句

时间:2016-04-08 19:27:55

标签: c#

我正在尝试让我的程序询问用户是否希望获得“超级英尺”,如果是,那么它将继续,但如果没有则程序应该说谢谢。有人能帮我辨别出我做错了什么吗?谢谢。

Console.Write("Would you like the super feet as well? ");
Console.ReadLine();

bool yes = true;
if (yes == true)
{
    Console.WriteLine("Please enter the following dims: ");
    Console.ReadLine();
}
else
{
    Console.WriteLine("Ok, Thank you");
    Console.ReadLine();
}

3 个答案:

答案 0 :(得分:1)

在测试条件之前尝试阅读您的答案。您还需要将答案存储在变量中。

Console.Write("Would you like the super feet as well? ");
var ans = Console.ReadLine();

bool yes = (ans == "yes");
if (yes == true)
{
  Console.WriteLine("Please enter the following dims: ");
  ...Code if yes is true...


}
   else
{
  Console.WriteLine("Ok, Thank you");
  ...Code if yes is false...
}

答案 1 :(得分:1)

你做错了两件事:

  1. 您没有阅读用户的任何输入,为此,您可以执行以下操作:

    string answer = Console.ReadLine();
    
  2. 您没有根据此输入为bool变量yes赋值,因此,您必须执行类似

    的操作
    if(answer == "yes")
        yes = true;
    else
        yes = false;
    
  3. 所以,在将这两个插入到你的代码之后,它会像:

    一样
        Console.Write("Would you like the super feet as well? ");
        string answer = Console.ReadLine();
    
        bool yes;
        if(answer == "yes")
            yes = true;
        else
            yes = false;
    
        if (yes == true)
        {
            Console.WriteLine("Please enter the following dims: ");
            Console.ReadLine();
        }
        else
        {
            Console.WriteLine("Ok, Thank you");
            Console.ReadLine();
        }
    

    当然,如果答案是"是"," yES"你可能也想将bool变量指定为true。等等,为了做到这一点,你可以使用answer = answer.ToLower()

答案 2 :(得分:0)

使用以下代码

Console.Write("Would you like the super feet as well? ");
string s =  Console.ReadLine();

///bool yes = true;
if (s.ToLower() == "yes")
{
    Console.WriteLine("Please enter the following dims: ");
    Console.ReadLine();
}
else
{
    Console.WriteLine("Ok, Thank you");
    Console.ReadLine();
}