C
C#14mo ago
LESZEK

✅ help

No description
20 Replies
LESZEK
LESZEKOP14mo ago
why its dont work
SinFluxx
SinFluxx14mo ago
Hover over the highlighted lines to get an idea of what's wrong
SinFluxx
SinFluxx14mo ago
for example:
No description
Angius
Angius14mo ago
Console.ReadLine() returns string? a is of type int Square peg does not fit round hole
SinFluxx
SinFluxx14mo ago
Also if you're assigning them to string variables straight after anyway, may as well cut out the middleman and get rid of int a
Angius
Angius14mo ago
And of Convert.ToString() Since it basically does "turn this string into a string"
LESZEK
LESZEKOP14mo ago
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
Angius
Angius14mo ago
a is still of type int
LESZEK
LESZEKOP14mo ago
in 4 line and in 7 line
Angius
Angius14mo ago
Did you read anything we said?
LESZEK
LESZEKOP14mo ago
so the int type cannot be converted to the string type?
Angius
Angius14mo ago
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
LESZEK
LESZEKOP14mo ago
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);
Angius
Angius14mo ago
Yes, this would be more correct
LESZEK
LESZEKOP14mo ago
ok because I didn't know that Ican't convert from string to int
ZacharyPatten
ZacharyPatten14mo ago
you can, just not implicitly
Angius
Angius14mo ago
You just did convert from a string to an int though? Convert.ToInt32() does just that Takes a string Returns an int
ZacharyPatten
ZacharyPatten14mo ago
but you should use int.Parse(...) instead of Convert.ToInt32(...) if you need to convert a string to an int
MODiX
MODiX14mo ago
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)
if(int.TryParse("123", out int number))
{
var total = number + 1;
Console.WriteLine(total); // output: 124
}
if(int.TryParse("123", out int number))
{
var total = number + 1;
Console.WriteLine(total); // output: 124
}
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

Did you find this page helpful?