使用布尔值的问题?

时间:2016-10-03 05:20:27

标签: c# visual-studio console console-application

我认为我试图完成的事情相当明显,但很明显,我对编码很新。这是我的代码,它可以正常工作,直到它进入"你想运行一个程序吗?"在这种情况下,它总是像用户输入"是"。我是否完全错误或者写错了?

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string mystring = "What is your name?";
            Console.WriteLine(mystring);
            string UserInput = Console.ReadLine();
            string Name = UserInput;
            Console.WriteLine("Hello " + Name);
            Console.WriteLine("Would you like to run a program?");
            bool UserIput2;
            Console.ReadLine();
            bool Yes = true;
            bool No = false;
            if (UserIput2 = (true)) Console.WriteLine("What would you like to run? (Type help for a list of valid programs)");
            else if (UserIput2 = (false)) Console.WriteLine("Goodbye");
            Console.ReadLine();
            Console.ReadLine();

        }
    }
}

3 个答案:

答案 0 :(得分:1)

试试这个,我在这里为UserIput2分配输入并将其与" yes"进行比较。或"不"。您可以将其更改为相应的

 string mystring = "What is your name?";
        Console.WriteLine(mystring);
        string UserInput = Console.ReadLine();
        string Name = UserInput;
        Console.WriteLine("Hello " + Name);
        Console.WriteLine("Would you like to run a program?");
        string UserIput2= Console.ReadLine();
        if (UserIput2.ToLower() == "yes") Console.WriteLine("What would you like to run? (Type help for a list of valid programs)");
        else if (UserIput2.ToLower() == "no") Console.WriteLine("Goodbye");
        Console.ReadLine();
        Console.ReadLine();

答案 1 :(得分:1)

在您当前的代码中,您丢弃用户输入:

Console.WriteLine("Would you like to run a program?");
bool UserIput2;
Console.ReadLine(); // <- input is discarded

相反,您应该分配给UserIput2

Console.WriteLine("Would you like to run a program?");

// we assume that answer is positive (UserIput2 == true) 
// if and only if user put "yes" in any register ("YES", "Yes", "yes"...)    
bool UserIput2 = String.Equals(
  Console.ReadLine(), 
  "yes", 
  StringComparison.OrdinalIgnoreCase);

if=的另一个问题是分配,而非比较

 if (UserIput2 = (true)) Console.WriteLine(...);

表示true分配给UserIput2,然后检查。正确的实施是

if (UserIput2) 
  Console.WriteLine("What would you like to run? (Type help for a list of valid programs)");
else 
  Console.WriteLine("Goodbye");

答案 2 :(得分:-1)

boolean类型是二进制。想象一下,这种类型的工作就像一个灯开关。它只能有2种状态 - true和关false。仅将此数据类型用于在两种可能状态之间切换。

示例C#:

bool result = (2 > 1); //Will result in true because 2 is great as 1

bool result = (2 < 1); //Will result in false because 2 is not less as 1