20 Replies
why its dont work
Hover over the highlighted lines to get an idea of what's wrong
for example:
Console.ReadLine()
returns string?
a
is of type int
Square peg does not fit round holeAlso if you're assigning them to string variables straight after anyway, may as well cut out the middleman and get rid of
int a
And of
Convert.ToString()
Since it basically does "turn this string into a string"string str1 , str2 ;
int a ;
Console.WriteLine("napisz 1 liczbe");
a = Console.ReadLine();
str1 = Convert.ToString(a);
Console.WriteLine("napisz 2 liczbe");
a = Console.ReadLine();
str2 = Convert.ToString(a);
string result = str1 + str2;
Console.WriteLine( "wynik " + result);
and now its have two mistake
a
is still of type int
in 4 line and in 7 line
Did you read anything we said?
so the int type cannot be converted to the string type?
Console.ReadLine()
returns a string?
Not an int
Not a bool
Not a DateTime
A string?
If you want to assign the value of Console.ReadLine()
to a variable, that variable must be of type string?
Not int
Not bool
Not DateTime
if i want it to work i must write this?
int str1 , str2 ;
string a ;
Console.WriteLine("napisz 1 liczbe");
a = Console.ReadLine(); str1 = Convert.ToInt32(a); Console.WriteLine("napisz 2 liczbe"); a = Console.ReadLine(); str2 = Convert.ToInt32(a); int result = str1 + str2; Console.WriteLine( "wynik " + result);
a = Console.ReadLine(); str1 = Convert.ToInt32(a); Console.WriteLine("napisz 2 liczbe"); a = Console.ReadLine(); str2 = Convert.ToInt32(a); int result = str1 + str2; Console.WriteLine( "wynik " + result);
Yes, this would be more correct
ok
because I didn't know that Ican't convert from string to int
you can, just not implicitly
You just did convert from a string to an int though?
Convert.ToInt32()
does just that
Takes a string
Returns an intbut you should use
int.Parse(...)
instead of Convert.ToInt32(...)
if you need to convert a string
to an int
When you don't know if a string is actually a number when handling user input, use
int.TryParse
(or variants, e.g. double.TryParse
)
TryParse
returns a bool
, where true
indicates successful parsing.
Remarks:
- Avoid int.Parse
if you do not know if the value parsed is definitely a number.
- Avoid Convert.ToInt32
entirely, this is an older method and Parse
should be preferred where you know the string can be parsed.
Read more here