Vane4ka
Vane4ka

Reputation: 3

Console.Read with int

I was studying c# one and a half ear ago. And I forgot a lot. Now I want to study it again. I wanted to do

        int answer;
        Console.WriteLine("What is the answer?");
        answer = Console.Read();
        if(answer == 1)
        {
            Console.WriteLine("You are good!");
        }
        else
            Console.WriteLine("You are dumb!");

And in the console I have this: enter image description here or enter image description here

Guys help please!!

Upvotes: 0

Views: 526

Answers (2)

Ibrahim Timimi
Ibrahim Timimi

Reputation: 3700

When you read char 1 from console, it equals int 49 as seen from the table below:

char     code
0 :      48
1 :      49
2:       50
...
9:       57

In your example it is better to use switch case rather than if-else.

static void Main(string[] args)
{
    Console.WriteLine("What is the answer?");
    var answer = Console.Read();
    switch (answer)
    {
        case 49: // 1
            Console.WriteLine("You are good!");
            break;
        default:
            Console.WriteLine("You are dumb!");
            break;
    }
    Console.WriteLine("Press Any key To Continue...");
}

Alternatively, you can use this to convert char to int automatically.

Console.WriteLine("What is the answer?");
var answer = Console.ReadKey().KeyChar;
Console.WriteLine();

switch (char.GetNumericValue(answer))
{
    case 1:
        Console.WriteLine("You are good!");
        break;
    default:
        Console.WriteLine("You are dumb!");
        break;
}

Upvotes: 0

Jeroen van Langen
Jeroen van Langen

Reputation: 22038

It's better to use the Console.ReadLine(). This way you can get more characters.

To parse it as an int, you use the int.TryParse()

example

int answer;
string answerStr;
Console.WriteLine("What is the answer?");
answerStr = Console.ReadLine();

if(int.TryParse(answerStr, out answer))
{
    if(answer == 1)
    {
        Console.WriteLine("You are good!");
    }
    else
        Console.WriteLine("You are dumb!");
}
else
    Console.WriteLine("You are even dumber! That's not a number!");

Upvotes: 0

Related Questions