Is there a version of string.IsNullOrWhiteSpace for integers?

2.1k views Asked by At

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 ?

1

There are 1 answers

1
Sergey Kalinichenko On

There is no equivalent of IsNullOrWhiteSpace for ints because int always represents a number.

I asked the user to input 3 of them and leave one empty.

One approach is to keep user input as strings up until the moment when you are ready to use its integer form:

Console.WriteLine("ilk aracın hızını giriniz");
string sv1 = Console.ReadLine();

Use IsNullOrWhiteSpace on sv1, sv2, sx, st, and then convert inside the if statement:

if (string.IsNullOrWhiteSpace(s1)) {
    v1 = Convert.ToInt32(sx) / Convert.ToInt32(st) - Convert.ToInt32(sv2);
    Console.WriteLine(v1);
}

Note that this is integer division, so any fractional result of dividing x by t is truncated.

Another approach is to use TryParse on all four values, and avoid IsNullOrWhitespace altogether:

Console.WriteLine("ilk aracın hızını giriniz");
bool missingV1 = !int.TryParse(Console.ReadLine(), out var v1);
Console.WriteLine("ikinci aracın hızını giriniz");
bool missingV2 = !int.TryParse(Console.ReadLine(), out var v2);
Console.WriteLine("yolun uzunluğunu giriniz");
bool missingX = !int.TryParse(Console.ReadLine(), out var x);
Console.WriteLine("karşılaşma sürelerini giriniz");
bool missingT = !int.TryParse(Console.ReadLine(), out var t);
if (missingV1) {
    v1 = x / t - v2;
    Console.WriteLine(v1);
} else if (missingV2) {
    ...
}