2017-02-15 52 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; 
}