jschmuff
asked on
Storing an int variable in a class
How do I store an int variable in a class that is input from the user from the main code?
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ReadLine return text.
validate the input and cast it to int
validate the input and cast it to int
That's because Console.ReadLine() returns a string (as it reads a string of characters from the console). In order to assign it to an integer property you must first convert it into an int.
The best way to do that for int's is to use the Parse method:
character.Life = int.Parse(Console.ReadLine ());
The string that is gotten from Console.ReadLine() is passed into the int.Parse function, which turns it into an integer (if it is indeed an integer representation) that you can then assign to character.Life.
The best way to do that for int's is to use the Parse method:
character.Life = int.Parse(Console.ReadLine
The string that is gotten from Console.ReadLine() is passed into the int.Parse function, which turns it into an integer (if it is indeed an integer representation) that you can then assign to character.Life.
ASKER
I get it output as a dollar value how do I get rid of that?
As you can see of my example, I convert the string value that's output from Console.ReadLine(). You should however use a try/catch block around it to avoid any problems with empty input or non-integer input.
ASKER
Program.cs(62,30): error CS0029: Cannot implicitly convert type 'string' to 'int'
Here is my code:
Open in new window