检查unicode字符的字符类型

时间:2018-06-12 20:21:13

标签: c# if-statement unicode char

我正在运行CodeEasy.net的c#程序,我偶然发现了一个我正在努力解决的问题。我不明白为什么不通过。

  

编写一个程序,从控制台读取一个char使用   Console.Read()和Convert.ToChar(...)方法。在此之后,   程序应输出"数字" "信"或"不是数字而不是数字   信"到屏幕,取决于角色是什么。

我也尝试过charCode = int.Parse(Console.ReadLine());而不是int charCode = Console.Read();,但似乎没有任何效果。它一直给我第一个" if"最后"其他"结果,但只有其中一个应该打印,所以它很混乱。

到目前为止,这是我的代码:

int charCode = Console.Read();
char theRealChar = Convert.ToChar(charCode);

if (char.IsDigit(theRealChar))
{
    Console.WriteLine("Digit");
}
if (char.IsLetter(theRealChar))
{
    Console.WriteLine("Letter");
}
else
{
    Console.WriteLine("Not a digit and not a letter");
}

非常感谢任何让我理解这一点的帮助!

2 个答案:

答案 0 :(得分:1)

您的else语句仅 与第二个if语句相关联。你有效地得到了:

if (firstCondition)
{
    // Stuff
}

// You could have unrelated code here

if (secondCondition)
{
    // Stuff
}
else
{
    // This will execute any time secondCondition isn't true, regardless of firstCondition
}

如果您只希望在以前的if语句的 中执行它,那么您需要第二个else if

if (char.IsDigit(theRealChar))
{
    Console.WriteLine("Digit");
}
// Only check this if the first condition isn't met
else if (char.IsLetter(theRealChar))
{
    Console.WriteLine("Letter");
}
// Only execute this at all if neither of the above conditions is met
else
{
    Console.WriteLine("Not a digit and not a letter");
}

答案 1 :(得分:0)

在第二个else阻止之前添加缺失的if后,似乎工作正常。

if (char.IsDigit(theRealChar))
{
    Console.WriteLine("Digit");
}
else if (char.IsLetter(theRealChar))
{
    Console.WriteLine("Letter");
}
else
{
    Console.WriteLine("Not a digit and not a letter");
}