如何检查输入是否与特定字母匹配?

时间:2017-03-27 14:32:56

标签: c#

我无法弄清楚如何检查输入是否是特定字母。我知道如何检查它是否是特定的int / double,但是如果它是string我不知道该怎么做。

非常感谢任何帮助。我只是尝试做一个基本的3个问题测验,检查用户是否用正确的字母(a,b或c)回答,然后将其添加到当前分数。

class Program
{
    static void Main()
    {
        var a1 = "a";
        var a2 = "b";
        var a3 = "c";
        var qa = 0;
        while (qa != 3)
        {
            if (qa == 0)
            {
                Console.Write("What is the answer to question 1? ");
                var entry1 = Console.Read();

                if()
                {

                }                                              
            }

            else if (qa == 1)
            {
                Console.Write("What is the answer to question 2? ");
                Console.ReadLine();
            }

            else if (qa == 2)
            {
                Console.Write("What is the answer to question 3? ");
                Console.ReadLine();
            }                
        }    
    }
}

4 个答案:

答案 0 :(得分:4)

  

例如,operator ==无法应用于字符串

这不是真的。它可以应用:

if(entry.ToString() == a1)

documentation for the == operator告诉我们:

  

对于字符串类型,==比较字符串的值

另一种可能性是使用String.Equals方法

if(entry.ToString().Equals(a1))

修改

仔细查看代码,我意识到您正在使用Console.Read  哪个

  

从标准输入流中读取下一个字符。

这意味着它返回char(并且只返回1)。

我想你想要用户输入的整行。所以你应该使用ReadLine代替。它返回string并允许您进行直接比较

string entry1 = Console.ReadLine();
if(entry == a1)

当您使用var进行类型声明时,编译器会推断出类型,并且错误在稍后阶段变得明显。您无法在==string上使用char运算符。 Read()会返回char,这就是为什么你无法在第一时间对它进行比较

答案 1 :(得分:1)

请注意"问题1"你写了Console.Read(),(而不是Console.ReadLine()),它返回一个字符,而不是一个字符串。所以" =="不能应用于entry1和a1,因为entry1将是char,而a1是字符串。

答案 2 :(得分:0)

如果比较兼容变量,一切都应该没问题

string input1;
var input2 = "";
var input3 = 0;

// assign some input values, then compare

// strings
if (input1 == "a") // ok
{ }
if (input2 == "a") // ok
{ }
if (input3 == "a") // not ok, comparing int to string
{ }
// numbers
if (input1 == 1) // not ok, comparing string to int
{ }
if (input3 == 1) // ok
{ }

答案 3 :(得分:0)

如果您愿意,可以尝试使用Console.Read();来匹配字符的ASCII值。这将消除按Enter键的需要。如果您尝试匹配大写A:

    int input = Console.Read();
    if (input == (int)char.GetNumericValue(A))
    {
        Console.WriteLine("True");
        Console.Read();

    }
    else
    {
        Console.WriteLine("False");
        Console.Read();

    }