简体   繁体   中英

The first console app in C#

I recently started to learn C#,so I tried to make something simple,but can not make the program to be 100% functional.I did it in Visual Studio and with every value given,the answer is the same

Bigger than 0

using System;

namespace ConsoleApplication1
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Please enter a number");
        int userinput = Console.Read();
        if (userinput > 0) Console.Write("Bigger than 0");
            else if (userinput < 0) Console.Write("Less than 0");
                    else Console.Write("Equal to 0");
        Console.Write("\nPress <ENTER> to exit\n");
        Console.ReadKey();

        }

}
}

The Console.Read() method read the code of the key pressed, not an integer value typed in the console. You have to use Console.ReadLine() to read the full string and convert it into an integer, like this:

int userinput = Convert.ToInt32(Console.ReadLine());

Note that in case the input string won't be a proper integer number, the program will fail. You can consider using Int32.TryParse() and handling invalid input.

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