并非所有代码路径都返回值。

时间:2014-02-26 08:12:56

标签: c# if-statement do-while

我故意设计了这段代码,我无法使用它。我可以覆盖这个故障安全吗?

do // Checks if the chosen name is also the right name
        {
            string test;
            Console.Write("Are you sure " + temp + " is the right name? (y/n)\n");
            test = Console.ReadLine();
            Console.Write("\n");
            if (test.ToLower() == "y")
            {
                nameIsRight = true;
                return temp;
            }
            else if (test.ToLower() == "n")
            {
                Console.Write("What is your name then?\n");
                temp = Console.ReadLine();
            }
            Console.Write("\n");
        } while (nameIsRight == false);

3 个答案:

答案 0 :(得分:2)

您应该在此循环之后添加return语句

do // Checks if the chosen name is also the right name
{
   //...
}while (!nameIsRight);

return something;

更新:正如@hvd所说,你总是从循环返回。所以,可能抛出异常是一种更好的方法。

UPDATE2:我认为最好的解决方案是摆脱布尔标志和内部返回语句:

do // Checks if the chosen name is also the right name
{
    Console.Write("Are you sure " + temp + " is the right name? (y/n)\n");
    key = Console.ReadKey().Key;
    Console.Write("\n");

    if (key == ConsoleKey.N)
    {
        Console.Write("What is your name then?\n");
        temp = Console.ReadLine();
    }

    Console.Write("\n");
} while (key != ConsoleKey.Y);

return temp;

答案 1 :(得分:0)

我宁愿做这样的事情:

编辑:更正的代码。

do // Checks if the chosen name is also the right name
{
    string test;
    Console.Write("Are you sure " + temp + " is the right name? (y/n)\n");
    test = Console.ReadLine();
    Console.Write("\n");
    if (test.ToLower() == "y")
    {
        nameIsRight = true;

    }
    else if (test.ToLower() == "n")
    {
        Console.Write("What is your name then?\n");
        temp = Console.ReadLine();
        continue;
    }
    else
    {
        Console.WriteLine("Incorrect input!!!");
        continue;
    }                
} while (nameIsRight == false);

return temp;

您不应该从循环内部返回变量,而只是将条件设置为true或false。

答案 2 :(得分:0)

学习编写更好的可读(和可维护)代码。

// Ask what you have to ask before the loop
Console.Write("Enter the name: \n");
string result = Console.ReadLine();

while(true) 
{
    Console.Write("Are you sure " + result + " is the right name? (y/n)\n");
    string test = Console.ReadLine();
    Console.Write("\n");
    if (test.ToLower() == "y")
    {
        // it will exit the loop
        break;
    }
    // when loop is not exited, keep asking until user answers with "y"
    Console.Write("What is your name then?\n");
    result = Console.ReadLine();
    Console.Write("\n");
};

// result will always contain the latest input, as it's not possible for the user to leave
// except closing the application
return result;

通过这种方式,你永远不会陷入这种情况,代码更具可读性,因为你可以清楚地看到循环离开时的中断,而你根本不需要在循环中返回任何内容并且你没有&#39 ; t需要管理循环条件(while (nameIsRight == false))。