2014-07-22 32 views
1

我無法弄清楚如何使用括號使我的程序檢查輸入是否爲數字。如果沒有,我想返回一個錯誤,然後重新啓動進程。有什麼建議麼?C#if語句readline必須等於數字

bool running = true; 

Console.Write("Enter the number of victims so we can predict the next murder, Sherlock: "); 

while (running) 
{ 
    victimCount = int.Parse(Console.ReadLine()); 

    if (/*I want victimCount only to be accepted if it's a number*/) 
    { 
     Console.Write("\nThat's an invalid entry. Enter a correct number!: "); 
    } 
    else 
    { 
     running = false; 
    } 
} 

回答

7

我想victimCount只是如果它是一個數字

您可以使用int.TryParse方法,而不是被接受。它返回boolean值,您的值是否有效int或不。

string s = Console.ReadLine(); 
int victimCount; 
if(Int32.TryParse(s, out victimCount)) 
{ 
    // Your value is a valid int. 
} 
else 
{ 
    // Your value is not a valid int. 
} 

Int32.TryParse方法默認使用NumberStyles.Integer。這意味着你的字符串可以有;

爲數字麥粒腫。

+0

非常感謝,它工作得很好! – Zentie

+0

@Zentie你很受歡迎。 –

+0

如果我想用double來做同樣的事情,而不是int,我該怎麼辦?我放什麼而不是「Int32.TryParse」? – Zentie

0

試試這個:

int victimcount; 
bool is Num = int.TryParse(Console.ReadLine(), out victimcount); 

If `isNum` is true then the input is an integer. Use this for your check. At the same time, if the parse succeeds, the parsed value gets assigned to the `victimcount` variable (0 is assigned if it fails).