Reputation: 15
I am very very new at C# and i am just trying a little code here.
But it didn't work. I don't understand why. And i dont get any erros on Visual Studio. It just doesn't work right. I alwasy says " You wrote a higher number. " and close.
Can you help me?
You can understand what i am trying to do.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int number = 4 ;
Console.WriteLine("Hello");
Console.WriteLine("Write a number from 1 to 10 : ");
int x = Console.Read();
if ( x < number )
Console.WriteLine("You write a lower number.");
else if ( x > number )
Console.WriteLine("You write a higher number.");
else
Console.WriteLine("True");
Console.Read();
}
}
}
Upvotes: 0
Views: 132
Reputation: 11976
Read only reads in the next character.
You want to use Console.ReadLine and convert the string to an integer using int.Parse or int.TryParse.
int x = int.Parse(Console.ReadLine());
Also, I suppose Read would work from numbers 0-9. The reason why You write a higher number
was always being outputted was because it was comparing the character value rather than the numerical value because Read returns the decimal representation of the character.
If you must use Read then you would have to obtain the numerical value from the character value like so:
int x = Console.Read();
int numericalX = (int)char.GetNumericValue((char)x);
Also, like others have recommended, I would advise using int.TryParse
rather than int.Parse
in the off-chance the given input is not a valid integral value. int.TryParse
returns a boolean value indicating whether or not the conversion was successful and outputs the converted integral value as an out parameter.
Upvotes: 6
Reputation: 10211
The first thing you should do is to verify value of x
. The Console.Read()
returns a char
value which can be implicitly casted into int
. So if you typed 3, the value of x
will be 51.
Upvotes: 0
Reputation: 190897
Its because Console.Read()
returns the character, not the number. Likely you want a ReadLine
then a call to int.TryParse
.
Upvotes: 2