使用while循环时出错

时间:2010-09-15 03:19:44

标签: 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");
        }
    }
}

5 个答案:

答案 0 :(得分:8)

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

你有:

do 
{

} while (criteria);
{
   // code you want to execute repeatedly
}

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

你应该只有:

while (criteria)
{
    // code you want to execute repeatedly
} 

省略do部分,因为这实际上会创建一个合法的循环,而不是您真正希望循环的代码。

编辑: @Randy,这是您第二次发布类似问题。您正在有效地尝试合并dowhile循环。转到MSDN and review loops。简而言之,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);

While 循环

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

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

答案 1 :(得分: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
}

答案 2 :(得分:0)

每个人都在纠正你的do / while循环语法,所以我不会强调这一点。

要允许用户输入不敏感的命令,您可以使用if(userIn.ToUpper() == "X")而不必检查这两种情况。

答案 3 :(得分:0)

就像你的情况一样,第一个语句是break,所以它从循环中出来而while中的语句不会被执行...

答案 4 :(得分:0)

你检查过这个是一个语法错误。

string myString =“X3”;         int i = 4;         int j = 0;         做         {             if(myString ==“X”+ j)             {                 打破;             }             J ++;         } while(j< 4);