做的时候不要用布尔测试C#循环

时间:2017-02-15 20:08:02

标签: c# loops boolean try-catch do-while

当bool correctInput变为false时,我的do while循环不会循环。它应该循环,直到从使用中正确输入输入。可接受的输入是大于零的整数。任何整数都将抛出try catch并将correctInput布尔值更改为false,从而导致循环。如果整数不大于零,则correctInput将变为false,从而导致循环。只有当用户输入正确的输入时,循环才会退出。当输入不正确时,它当前没有循环。

  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);

    }

4 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

根据您的说明,如果长度小于为零,则您希望将correctInput设置为false,但如果大于,则代码会将其设置为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
            }

答案 2 :(得分:0)

根据您在此块中的注释,if块中的操作符错误:

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

如果要在输入小于0时将correctInput更改为false,则需要

if (Length < 0)

答案 3 :(得分:0)

这部分循环中的问题不是吗?

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

不应该这样读吗?

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