I'm fairly new to C# and programming in general and I've spent hours on trying to fix my basic program . I have 4 variables , I asked the user to input 3 of them and leave one empty . The program does calculations on the empty one but the problem is that I can't use the IsNullOrWhiteSpace for ints .
Console.WriteLine("ilk aracın hızını giriniz");
int v1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("ikinci aracın hızını giriniz");
int v2 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("yolun uzunluğunu giriniz");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("karşılaşma sürelerini giriniz");
int t = Convert.ToInt32(Console.ReadLine());
if (string.IsNullOrWhiteSpace(v1))
{
v1 = x / t - v2;
Console.WriteLine(v1);
}
else if (string.IsNullOrWhiteSpace(v2))
{
v2 = x / t - v1;
Console.WriteLine(v2);
}
else if (string.IsNullOrWhiteSpace(t))
{
t = x / (v1 + v2);
Console.WriteLine(t);
}
else if (string.IsNullOrWhiteSpace(x))
{
x = (v1 + v2) * t;
Console.WriteLine(x);
}
` Is there a way to fix this ? If so how ?
There is no equivalent of
IsNullOrWhiteSpace
forint
s becauseint
always represents a number.One approach is to keep user input as
string
s up until the moment when you are ready to use its integer form:Use
IsNullOrWhiteSpace
onsv1
,sv2
,sx
,st
, and then convert inside theif
statement:Note that this is integer division, so any fractional result of dividing
x
byt
is truncated.Another approach is to use
TryParse
on all four values, and avoidIsNullOrWhitespace
altogether: