使用while循环时出错

use*_*022 0 c# loops while-loop

while循环不起作用.当它遇到休息时退出循环时我得到一个错误.错误是没有循环语句来突破.

static void Main(string[] args)
{
    accounts myclass = new accounts();
    string userin;


    myclass.fillAccounts();
    //int i = 0;
    //while (i != 1)
    do
    {
    }
    while (userin != "x")
    {
        //use the following menu:            
        Console.WriteLine("*****************************************");
        Console.WriteLine("enter an a or A to search account numbers");
        Console.WriteLine("enter a b or B to average the accounts");
        Console.WriteLine("enter an x or X to exit program");
        Console.WriteLine("*****************************************");
        Console.Write("Enter option-->");
        userin = Console.ReadLine();
        if (userin == "a" || userin == "A")
        {
            myclass.searchAccounts();
        }
        else if (userin == "b" || userin == "B")
        {
            myclass.averageAccounts();
        }
        else if (userin == "x" || userin == "X")
        {
            break;
        }
        else
        {
            Console.WriteLine("You entered an invalid option");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ant*_*ram 8

就代码而言,您已设法将主体置于实际循环之下.

你有:

do 
{

} while (criteria);
{
   // code you want to execute repeatedly
}
Run Code Online (Sandbox Code Playgroud)

因此,您会收到break语句的错误消息,因为它实际上并不包含在循环中.

你应该只有:

while (criteria)
{
    // code you want to execute repeatedly
} 
Run Code Online (Sandbox Code Playgroud)

省略do部分,因为它实际上在你真正想要循环的代码之上创建一个合法的循环.

编辑: @Randy,这是您第二次发布类似问题.您正在有效地尝试将循环dowhile循环结合起来.转到MSDN并查看循环.简而言之,while循环检查循环体之前的条件,do循环检查循环体之后.该do循环也使用while关键字,以及可能混淆你.

待办事项循环

do
{
    // your code...
    // this loop is useful when you want the loop to execute at least once, since  
    // the exit condition will be evaluated *after* the first iteration
} while (condition);
Run Code Online (Sandbox Code Playgroud)

尽管

while (condition)
{
    // your code...
    // this loop is useful when you want to prevent *any* iterations unless the 
    // original boolean condition is met.
}
Run Code Online (Sandbox Code Playgroud)

这是两个单独的循环结构.组合它们不会使循环乐趣加倍,它只是创建一个循环(do),然后是另一个代码块.


In *_*ico 6

因为它不在循环体中.

do 
{ 
    // This is the do-while loop body.
    // You should put the code to be repeated here.
    break; // does work
} 
while(...)
{ 
    // This is not the do-while loop body.
    // This is just an ordinary block of code surrounded by the curly braces
    // and therefore declares a local scope. Variables declared in this
    // block is not visible outside the braces.
    break; // doesn't work
}
Run Code Online (Sandbox Code Playgroud)