Ame
Ame

Reputation: 47

Checking what type of character the unicode character is

I am running through CodeEasy.net's c# program and I have stumbled across a problem I am struggling with. I don't understand why this does not pass.

Write a program that reads from the console one char using Console.Read() and Convert.ToChar(...) methods. After this, the program should output "Digit" "Letter" or "Not a digit and not a letter" to the screen, depending on what the character is.

I have tried int charCode = int.Parse(Console.ReadLine()); as well instead of int charCode = Console.Read(); but nothing seems to work. It keeps giving me the first "if" and last "else" result, but only one of these should print so it is very confusing.

Here is my code so far:

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");
}

Any help in making me understand this is much appreciated!

Upvotes: 0

Views: 61

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503519

Your else statement is only associated with the second if statement. You've effectively got:

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 you only want it to execute if neither of the earlier if statements, you need the second one to be 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");
}

Upvotes: 1

Dan Wilson
Dan Wilson

Reputation: 4057

Seems to work fine once you add a missing else before the second if block.

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");
}

Upvotes: 0

Related Questions