how to read integer value - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

how to read integer value

veer_elluriveer_elluri Posts: 8Member
i am facing problems with reading a integer value from command line and assign to a integer variable.

my code is

using System;
class first
{
public static void main()
{
int a,b;
a=Console.Readline();
Console.WriteLine(a);
}
}

when i execute above message i am being displayed a error

not possible to convert 'string' to 'int'.


bye...

Comments

  • A. L.A. L. Posts: 7Member
    : i am facing problems with reading a integer value from command line and assign to a integer variable.
    :
    : my code is
    :
    : using System;
    : class first
    : {
    : public static void main()
    : {
    : int a,b;
    : a=Console.Readline();
    : Console.WriteLine(a);
    : }
    : }
    :
    : when i execute above message i am being displayed a error
    :
    : not possible to convert 'string' to 'int'.
    :
    :
    : bye...

    Try it this way:
    a=Int32.Parse(Console.Readline());
    just because the Console.Readline() method returns a string. However, if you'll enter something else than an int("ak2322" for example or even 3.5), you'll get an error. To avoid the interruption of your application in this case, use a try-catch block:
    try{
    a=Int32.Parse(Console.Readline());}
    catch(Exception ex){
    Console.Writeline(ex.Message);}

Sign In or Register to comment.