2013-10-04 57 views
1

對於程序,如果用戶輸入的數字不是0或更高,那麼程序會說「無效,輸入一個0或更高的數字」。程序會繼續說「無效,輸入0或更高的數字」。一次又一次地輸入數字0或更高。C#:如何創建一個只接受0或更高整數值的程序?

問題是,如果我輸入一個字母,程序不會迴應「無效,輸入0或更高的數字」。

這是我目前可以做的:

class Program 
    { 
     static void Main(string[] args) 
     { 
      string numberIn; 
      int numberOut; 

      numberIn = Console.ReadLine(); 

      if (int.TryParse(numberIn, out numberOut)) 
      { 
       if (numberOut < 0) 
       { 
        Console.WriteLine("Invalid. Enter a number that's 0 or higher."); 
       Console.ReadLine(); 
       } 
      }   
     } 
    } 

回答

2

替換爲您若的:

while (!int.TryParse(numberIn, out numberOut) || numberOut < 0) 
{ 
    Console.WriteLine("Invalid. Enter a number that's 0 or higher."); 
    numberIn = Console.ReadLine(); 
} 
3

你需要某種類型的循環。也許while循環:

static void Main(string[] args) 
{ 
    string numberIn; 
    int numberOut; 

    while (true) 
    { 
     numberIn = Console.ReadLine(); 

     if (int.TryParse(numberIn, out numberOut)) 
     { 
      if (numberOut < 0) 
      { 
       Console.WriteLine("Invalid. Enter a number that's 0 or higher."); 
      } 
      else 
      { 
       break; // if not less than 0.. break out of the loop. 
      } 
     }  
    } 

    Console.WriteLine("Success! Press any key to exit"); 
    Console.Read(); 
} 
0

如果你想要一個簡潔,利落的方法,你可以使用這個:

while (Convert.ToInt32(Console.ReadLine()) < 0) 
{ 
    Console.WriteLine("Invalid entry"); 
} 

//Execute code if entry is correct here. 

用戶輸入號碼時,它都會檢查是否輸入的號碼是小於0.如果輸入無效,則while循環繼續循環。如果輸入有效,則條件爲false,循環關閉。

相關問題