2017-02-15 36 views
0

當bool correctInput變爲false時,我的while循環將不會循環。它應該循環直到輸入從使用中正確輸入。可接受的輸入是大於零的整數。任何是整型的都會拋出try catch,並將correctInput boolean更改爲false,從而導致循環。如果整數不大於零,則correctInput將變爲false,導致循環。只有當用戶輸入正確的輸入時,循環纔會退出。當輸入不正確時,它當前不會循環。雖然不會循環使用布爾測試C#

private static void InputMangementShapeSquare() 
    { 
     bool correctInput = true; 
     int Length = 0; 
     string rawInput; 
     do 
     { 
      correctInput = true; 

      Console.WriteLine("Enter the Length: "); 
      rawInput = Console.ReadLine(); 
      try 
      { 
       Length = Int32.Parse(rawInput); 
       if (Length > 0) 
       { 
        correctInput = false; //Changes correctInput to false if input is less than zero 
       } 
      } 
      catch (Exception exception) 
      { 
       correctInput = false; //Changes correctInput flag to false when rawinput failed to be converted to integer. 
       Console.WriteLine("input must be an interger greater than zero.");      
      } 

     } while (correctInput == false); 

     Square square = new Square(Length); 

    } 

回答

1

從你的描述,你想,如果長度爲小於零,但你的代碼將其設置爲false,如果它比零的correctInput被設置爲false。

  if (Length > 0) 
      { 
       correctInput = false; //Changes correctInput to false if input is less than zero 
      } 

它應該是:

  if (Length <= 0) 
      { 
       correctInput = false; //Changes correctInput to false if input is less than zero 
      } 
+0

只是看到了...... / – DigitalDulphin

2

我會改變if

if (Length <= 0) { 
    correctInput = false; //Changes correctInput to false if input is less than zero 
} 

C#,你也可以使用TryParse,所以你不需要try catch

int value; 
if (!int.TryParse(rawInput, out value)) { 
    correctInput = false; 
} 

而同樣與您的代碼:

correctInput = false; 
do { 
    Console.WriteLine("Enter the Length: "); 
    rawInput = Console.ReadLine(); 

    int value; 
    if (int.TryParse(rawInput, out value) && value >= 0) { 
     correctInput = true; 
    } else { 
     Console.WriteLine("input must be an interger greater than zero."); 
    } 
} while (!correctInput); 
0

基於在此塊你的評論,你打錯了運營商在if塊:

if (Length > 0) 
    { 
      correctInput = false; //Changes correctInput to false if input is less than zero 
    } 

如果你想改變correctInput到假如輸入小於0那麼它需要是

if (Length < 0) 
0

在這部分循環中不是問題嗎?

if (Length > 0) 
{ 
    correctInput = false; //Changes correctInput to false if input is less than zero 
} 

不應該這樣讀取嗎?

if (Length < 0) 
{ 
    correctInput = false; 
}