Page 1 of 1

simple C# question!

Posted: Tue Sep 21, 2010 9:58 pm
by Trebor29
Hi,
Ive just started learning C# with VFisual Basic 2010 and this is only the second program lol..! I know is very similar to JAVA but im not doing something right...!
Can anyone tell me why this is not reading 'if (num <= 9)'.... for some reason when I Debug, if I input a 9, num becomes 57 and so obviously jumps to the 'else if'.

Code: Select all

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NumberRange
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please input a number.");
            int num = Console.Read();
            if (num <= 9)
            {
                Console.WriteLine("This number is within the specified range.");
            }
            else if (num > 9)
            {
                Console.WriteLine("Sorry, this number is out of range.");
                Console.WriteLine("Please try another.");
            }
        }
    }
}
Thank you... :roll:

Re: simple C# question!

Posted: Wed Sep 22, 2010 12:37 pm
by Neo
Use int num = int.Parse(Console.ReadLine()); instead of int num = Console.Read();.

Re: simple C# question!

Posted: Wed Sep 22, 2010 9:14 pm
by Trebor29
Hi Neo,

Thanks 'again' for your help... It is only you who replies to my questions.. lol
So what is '.Parse'?? and can you tell me why it was calculating those crazy numbers before...?

Cheers. Trebor :ugeek:

Re: simple C# question!

Posted: Wed Sep 22, 2010 9:22 pm
by Neo
It was reading console input as a string/char and you need to get is parsed as an integer (number value).

Re: simple C# question!

Posted: Wed Sep 22, 2010 10:47 pm
by Trebor29
erm... just out of curiosity Neo, Why was it reading Console input as a string when I declared the variable 'num' as an int? Is this just one of the differences from using JAVA?
They will probably go over this next week but I like to get ahead of the class. ;)

Re: simple C# question!

Posted: Thu Sep 23, 2010 4:28 am
by Neo
You will need to understand a programming point here.
When you define it as int num = myfunction(); there is no effect to myfunction() function from "int" since you do not pass it as a parameter to it. Within the function, there is no way to identify that you are going to assign the function return to an "int".

If you consider the definition of the function, you will notice that it returns a string. You can't assign a string to an "int" directly without converting it to a number.

Re: simple C# question!

Posted: Thu Sep 23, 2010 9:54 pm
by Trebor29
Hummm.... interesting! I still have much to learn "said the young apprentice" :)
Thanks Neo.