2012-03-13 54 views
2

我有與其中我想如果用戶輸入了正確格式化數字值,以檢測一個簡單的控制檯應用一個小問題。 也就是說,如1212sss或類似asjkq12323或單個字符的值不被接受。我想只接受純整數值。支票有效數量的輸入 - 控制檯應用程序

這是我曾嘗試

bool detectNumber(string s) 
{ 
    int value=0; 
    Int.TryParse(s,out value); 
    return (value!=0)?true:false; 
} 

我感謝所有幫助。謝謝soooo多,,,,,

+1

,什麼是你已經嘗試了什麼問題? – 2012-03-13 08:26:45

+0

我不會寫做** **究竟什麼'int.TryParse'呢... – gdoron 2012-03-13 08:31:10

+0

其實沒有什麼錯都在那邊,我只是想和大家分享的TryParse的結果的方法。 – Hoger 2012-03-13 08:34:14

回答

1
string line = Console.ReadLine(); 
int value; 
if (int.TryParse(line, out value)) 
{ 
    Console.WriteLine("Integer here!"); 
} 
else 
{ 
    Console.WriteLine("Not an integer!"); 
} 
+0

我接受你的回答,因爲你看到你的信譽最低。同意? :-D – Hoger 2012-03-13 08:38:45

3

TryParse返回一個布爾值。檢查一下,不是通過out參數傳遞的值。

if(int.TryParse(s, out value)) 
{ 
    // do something 
} 

或者只是:

return int.TryParse(s, out value); 

順便說一句,這是沒有必要的初始化值使用out關鍵字過去了。聲明參數的方法必須在返回之前對其進行初始化。

int foo; // legal 
int.TryParse("123", out foo); 

所有BCL「嘗試」的方法遵循相同的約定(如double.TryParse()浮點數,如@gdoron在評論中提到的)。

而對於好奇,source code爲實現int.TryParse()的底層庫。

+0

浮動數字呢? 'double.TryParse' ... – gdoron 2012-03-13 08:32:09

2
int value = 0; 
bool ok = int.TryParse(s, out value); 
return ok; 
1

有幾種方法來測試只有數字編號:

首先,從來沒有使用Int因爲它的最大值,要麼使用intInt32

解析
int result; 
if (int.TryParse("123", out result)) 
{ 
    Debug.WriteLine("Valid integer: " + result); 
} 
else 
{ 
    Debug.WriteLine("Not a valid integer"); 
} 

Convert.ToInt32()

// throws ArgumentNullExceptionint 
result1 = Int32.Parse(null); 

// doesn't throw an exception, returns 0 
int result2 = Convert.ToInt32(null); 

則IsNumeric()

using Microsoft.VisualBasic; 
// ...... 
bool result = Information.IsNumeric("123"); 

模式匹配

string strToTest = "123"; 
Regex reNum = new Regex(@"^\d+$"); 
bool isNumeric = reNum.Match(strToTest).Success; 
0

你的代碼工作正常,你只能重構一下。下面的代碼是短,但不完全一樣:

static bool IsInt32(string s) 
{ 
    int value; 
    return Int32.TryParse(s, out value); 
} 
相關問題