2014-11-04 28 views
-1

我在這裏玩東西,並且遇到了麻煩。在if/else中創建一個int並稍後使用它

我有一個輸入;它可以是數字或字母。我必須檢查它是一個數字還是一個字母。所以我使用了if。如果輸入是一個數字,我的代碼應該創建一個int。如果它是一個字母,它應該創建一個不同的int。但由於某種原因,我以後不能使用整數。任何方式來解決這個問題?

Console.WriteLine("Length (ms)"); 
string I = Console.ReadLine(); 
int I2 = Int32.Parse(I); 
Console.WriteLine("Height: r for random"); 
string L = Console.ReadLine(); 
//So it asks for an input,for which I here want to check what it is 
if (L != "r") 
{ 
    int He = Int32.Parse(L); 
} 
else 
{ 
    Random Hi = new Random(); 
    int He = Hi.Next(1, 50); 
} 
//----------------------I want to use the ints in here 
while(true) 
{ 
    Random R = new Random(); 
    Random R2 = new Random(); 
    int H = R2.Next(1,He); 
    int rH = H * 100; 
    Console.WriteLine("Height is {0}",H); 
    Console.Beep(rH,I2); 
+2

在前面的範圍中定義它。 – 2014-11-04 15:42:59

+2

在if語句之外聲明'int He;',然後在語句內部賦值。在這個問題上搜索關鍵字是「範圍」。聲明參數的範圍基本上是它聲明的最裏面的塊。 – Chris 2014-11-04 15:44:25

+0

[Name age在當前上下文中不存在]的可能重複(http://stackoverflow.com/questions/23092403/name-age-does-未存在-在最當前上下文) – Default 2014-11-04 15:54:43

回答

1

您需要調整的int He範圍,把它的條件塊之外。

int He; 
if (L != "r") 
{ 
    He = Int32.Parse(L); 
} 
else 
{ 
    Random Hi = new Random(); 
    He = Hi.Next(1, 50); 
} 

您也可以使用conditional operator在這個例子中,以使代碼看起來像這可能是最好的一個風格問題。

int He = L != "r" ? Int32.Parse(L) : (new Random()).Next(1, 50); 

有一點是值得注意的,關於上述兩項內容,版本是Int32.Parse可以提高一個數量基礎上,string L的格式,你可能要處理或者使用try - catch語句異常或使用TryParse方法

相關問題