简体   繁体   中英

C# Noob Looking for Little Help : Why this mini code doesnt works?

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

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.

Its because Console.Read() returns the character, not the number. Likely you want a ReadLine then a call to int.TryParse .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM