2017-10-11 93 views
2

我有這個代碼,我輸入一個名稱,然後一個整數。然後應用程序將根據指定的整數重複輸入的名稱。我遇到的問題是,我只希望用戶能夠重複名稱最多10次,最小爲1.這是我迄今爲止的。如何強制控制檯只接受一定範圍內的數字?

Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: "); 
string Name = Console.ReadLine(); 

Console.Write("Enter the number of times you wish for me to repeat your name, " + Name); 
int number = Int32.Parse(Console.ReadLine()); 

for (int i = 0; i < number; i++)   
    Console.WriteLine(""+ Name); 
Console.ReadKey(); 

編輯:如果有人認爲做什麼我有一個簡單的方法,我會很樂意給點建議!

+0

您可以添加您嘗試過的任何代碼以執行期望的限制嗎? – mrtig

回答

1

您需要過濾和驗證包裹的ReadLine()如果輸入數目是最小的1,並且最大的10 ,然後打印名稱。你可以這樣做:

Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: "); 
     string Name = Console.ReadLine(); 

     Console.Write("Enter the number of times you wish for me to repeat your name, " + Name); 

     int number = 0; 

     do 
     { 
      Int32.TryParse(Console.ReadLine(), out number); 
      if (number > 10 || number < 1) 
       Console.WriteLine("Please input numbers between 1 to 10"); 

     } while (number > 10 || number < 1); 

      for (int i = 0; i < number; i++) 
       Console.WriteLine("" + Name); 
     Console.ReadKey(); 

我正在做一個do-while循環這裏。除非滿足while循環,否則它將持續驗證數字是否在指定的範圍內,否則將退出並打印名稱。

0

你可以在while語句

實施例是

int number = -1; 
while(number < 1 || number > 10) 
{ 
     //Input code 
} 
//for loop goes under here 
1
static void Main(string[] args) 
    { 
     Console.Write("PLEASE ENTER YOUR FIRST AND LAST NAME: "); 
     string Name = Console.ReadLine(); 

     Console.Write("Enter the number of times you wish for me to repeat your name"); 
     var input = Console.ReadLine(); 
     int number = -1; 
     while (!int.TryParse(input, out number)) { 
      Console.WriteLine("Incorrect Value"); 
      Console.Write("Enter the number of times you wish for me to repeat your name"); 
      input = Console.ReadLine(); 
     } 

     for (int i = 0; i < number; i++) 
     { 
      Console.WriteLine("" + Name); 
      if (i == 9) 
      { 
       Console.WriteLine("End Program"); 
       break; 
      } 
     } 

     Console.ReadKey(); 

    } 
相關問題