2017-08-27 51 views
-2

我對C#和編程一般都很陌生,我花了幾個小時試圖修復我的基本程序。我有4個變量,我要求用戶輸入3個變量,並留下一個空的變量。該程序對空白進行計算,但問題是我無法使用IsNullOrWhiteSpace作爲整數。是否有整數的string.IsNullOrWhiteSpace版本?

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); 
} 

` 有沒有辦法解決這個問題?如果是這樣如何?

+3

可空INT''INT嘗試 –

+0

雙N;? bool isNumeric = Int.TryParse(「5」,out n); – Sujatha

+0

爲什麼不對源字符串執行'IsNullOrWhitespace()'而不是立即(並且沒有任何驗證)將它們轉換爲'int'? –

回答

5

對於int s,沒有相應的IsNullOrWhiteSpace,因爲int總是代表一個數字。

我要求用戶輸入3個,並留下一個空的。

一種方法是讓用戶輸入string s上行,直到那一刻,當你準備使用它的整數形式:

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

使用IsNullOrWhiteSpacesv1sv2sxst,然後在if聲明內轉換:

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

請注意,這是inte ger分割,所以x除以t的任何分數結果都被截斷。

另一種方法是在所有四個值使用TryParse,避免IsNullOrWhitespace乾脆:

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) { 
    ... 
} 
+0

... int不知道任何空格作爲字符串:o) –