0

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!!

Vane4ka
  • 3
  • 2
  • Console.Read() returns the **character code value** of the inputted character. Ever heard about ASCII codes or Unicode codes? For example, if you input the character `1`, Console.Read() will return 49. If you forget a lot (that happens), it would be prudent to consult the official documentation for the methods and classes you are using, especially if your program doesn't behave as you expect. Also refreshing your debugging skills is not a bad idea, as using the debugger would reveal to you what the actual value of the `answer` variable is after inputting a character... –  Oct 01 '22 at 17:59

2 Answers2

0

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!");
Jeroen van Langen
  • 21,446
  • 3
  • 42
  • 57
  • 1
    Nice "dad rap" rhyme there at the end. That alone deserves an upvote... ;-) –  Oct 01 '22 at 18:07
0

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;
}
Ibrahim Timimi
  • 2,656
  • 5
  • 19
  • 31