简体   繁体   English

C#:方法故障(没有封闭循环可以中断或继续)

[英]C#: Method Malfunction (no enclosing loop out of which to break or continue)

Newb here working there way toward being a hobbyist. 纽伯在这里努力成为一名业余爱好者。

My current project uses methods, classes, list to display books and comments and to allow users to enter their own comments in a console view. 我当前的项目使用方法,类,列表来显示书籍和评论,并允许用户在控制台视图中输入自己的评论。 I've built my classes and they are working at this time so I've expunged them for the moment to expose my current problem as clearly as possible. 我已经建立了我的班级,并且它们现在都在工作,因此暂时删除它们以尽可能清楚地揭示我当前的问题。 get at my problem which is that I felt my program was getting kind of big quickly so it seemed like a good idea to move some of the code into a method which i called 'Select'. 解决我的问题是,我觉得我的程序正在变得越来越大,因此将一些代码移到我称为“选择”的方法中似乎是个好主意。 Before i moved the code into the select method, it worked fine/as expected. 在将代码移入select方法之前,它工作正常/符合预期。 But now i'm getting error when i test: no enclosing loop out of which to break 但是现在我在测试时遇到错误:没有封闭循环可以中断

The specific error happens on the else if (command == "e"){break;} line 特定错误发生在else if (command == "e"){break;}行上

I've tried swapping the keyword 'break' for 'continue', but that did not work. 我尝试将关键字“ break”替换为“ continue”,但这没有用。 I've looked around the net and stackoverflow, but not found anything that i can understand well enough with my level of understanding to resolve (I'm still a newb). 我环顾了整个网络和stackoverflow,但没有发现我可以解决的任何知识(我还是个新手)。

Code: 码:

    class Program
{
    public void Play(){
        Announcer(" \n\nProgram Name Goes Here \n\n");

        while (true)
        {
            /*
             * Allow user to display director of books (Three)
             * allow user to select specific book with any comments it might have (2-4 comments)
             * Allow user to enter a specific comment
             * display book with new new added comment
             * Allow user to exit book
             * */
            Select();                
        Console.Read();
        }
    }


    public void Announcer(String strTxt){Console.Write(strTxt);}

    public String GetString(String strData){
        Console.WriteLine(strData);
        return Console.ReadLine();//traffic control => back to program
    }

    public void Select(){
        String command = GetString(" \n\n(V)eiw, (S)elect, (C)omment, (R)emove, (E)xit").ToLower();

            if (command == "v")
            { Announcer(" \n\nEnter listing: ");
              //ViewDirectory();//call view directory here
            }

            else if (command == "c")
            { Announcer(" \n\nEnter comment: "); }

            else if (command == "s")
            {                   
                //we want to do a selectString method that returns length of selects here
                String select = GetString(" \n\n(1)st Selection, (2)nd Selection, (3)rd book, (E)xit").ToLower();
                if (select == "1")
                { Announcer(" \n\nDisplay book info + allow for user comment entering"); }

                else if (select == "2")
                { Announcer(" \n\nDisplay book info + allow for user comment entering"); }

                else if (select == "3")
                { Announcer(" \n\nDisplay book info + allow for user comment entering"); }                
            }

            else if (command == "e") { break; }
            else { Console.WriteLine("\n\nOopsy, I don't know that command! \n\n"); }
        }
    }

    //public void ViewDirectory(){
    //    Console.WriteLine("stuff");

    //}

好吧,您不在循环中,因此要终止该方法的执行,关键字为“ return”

After you refactored your code, it's no longer aware that it's inside of a while loop, so the break keyword is unnecessary. 重构代码后,它不再知道它在while循环内,因此break关键字是不必要的。

You were using break to terminate the program, so you'll need to do something else to exit the while loop. 您正在使用break终止程序,因此您需要做其他事情以退出while循环。 There are multiple ways you could refactor, but you could try: 您可以采用多种方法进行重构,但是可以尝试:

while (true)
{
    var command
      = GetString(" \n\n(V)eiw, (S)elect, (C)omment, (R)emove, (E)xit").ToLower();

    if (command == "e")
        break;

    Select(command);

    Console.Read();
}

Pass command to Select() , so most of your logic is still in the other method... just don't test for command == "e" in Select() . command传递给Select() ,因此您的大多数逻辑仍然在其他方法中...只是不要在Select()测试command == "e"

Just omit the break; 只是忽略break; statement as there is no need for it, it is only required when you want to quit executing a loop. 语句,因为它不需要它,仅当您要退出执行循环时才需要它。

Problem : you can't break from if block as it is not enclosed in any loop . 问题:您无法脱离if block因为它没有包含在任何loop

Solution : You just return the status of the condition from the if block to ensure the loop breaks from the caller function . 解决方案:您只需从if block返回条件的状态,以确保循环从调用程序函数中中断。

1. if the command equals to "e" return the true so that caller breaks the loop. 1.如果命令等于“ e”,则返回true,以便调用者中断循环。
2. else return the false so that loop continues. 2. else返回false,以便循环继续进行。

 class Program
{
    public void Play(){
    Announcer(" \n\nProgram Name Goes Here \n\n");

    while (true)
    {
        /*
         * Allow user to display director of books (Three)
         * allow user to select specific book with any comments it might have (2-4 comments)
         * Allow user to enter a specific comment
         * display book with new new added comment
         * Allow user to exit book
         * */
         if(Select())
             break;   //break if you get return value of Select() as true
         Console.Read();
     }
}


 public bool Select(){
    String command = GetString(" \n\n(V)eiw, (S)elect, (C)omment, (R)emove, (E)xit").ToLower();

        if (command == "v")
        { Announcer(" \n\nEnter listing: ");
          //ViewDirectory();//call view directory here
         return false;
        }

        else if (command == "c")
        { Announcer(" \n\nEnter comment: ");  return false;}

        else if (command == "s")
        {                   
            //we want to do a selectString method that returns length of selects here
            String select = GetString(" \n\n(1)st Selection, (2)nd Selection, (3)rd book, (E)xit").ToLower();
            if (select == "1")
            { Announcer(" \n\nDisplay book info + allow for user comment entering"); }

            else if (select == "2")
            { Announcer(" \n\nDisplay book info + allow for user comment entering"); }

            else if (select == "3")
            { Announcer(" \n\nDisplay book info + allow for user comment entering"); }                

             return false;           
           }

        else if (command == "e") { return true; }
        else { Console.WriteLine("\n\nOopsy, I don't know that command! \n\n"); return 
          false; }
    }
}

break keywords work with loop or switch block. break关键字可用于循环或开关块。 In Select method there is no such statements. 在Select方法中,没有这样的语句。 you can return true/false from Select method and inside play method you can call break base on return value; 您可以从Select方法和在play方法内部返回true / false ,可以根据返回值调用break

if(Select())
{
     break;
}

I would update your Select method to return a boolean value indicating that the input was valid. 我将更新您的Select方法以返回一个布尔值,该布尔值指示输入有效。 Then, you can set the while condition as follows: 然后,可以如下设置while条件:

while (Select())
{
    /*
     * Allow user to display director of books (Three)
     * allow user to select specific book with any comments it might have (2-4 comments)
     * Allow user to enter a specific comment
     * display book with new new added comment
     * Allow user to exit book
     * */     
    Console.Read();
}

I would also discourage the use of many else if's like you have, and update them to use switch/case instead. 如果您喜欢的话,我也将不鼓励使用其他许多功能,并更新它们以使用switch / case。 For case s, you can also make that into a separate method. 对于case,您也可以将其设为单独的方法。

public bool Select()
{
    bool isValid = true;
    String command = GetString(" \n\n(V)eiw, (S)elect, (C)omment, (R)emove, (E)xit").ToLower();

    switch (command)
    {
        case "v":
            Announcer(" \n\nEnter listing: ");
        //ViewDirectory();//call view directory here
            break;
        case "c":
            Announcer(" \n\nEnter comment: ");
            break;
        case "s":
        {
            //we want to do a selectString method that returns length of selects here
            String select = GetString(" \n\n(1)st Selection, (2)nd Selection, (3)rd book, (E)xit").ToLower()

            switch (select)
            {
                case "1":
                    Announcer(" \n\nDisplay book info + allow for user comment entering"); 
                    break;
                case "2":
                    Announcer(" \n\nDisplay book info + allow for user comment entering");
                    break;
                case "3":
                    Announcer(" \n\nDisplay book info + allow for user comment entering");
                    break;
            }
            break;
        }
        case "e":
            isValid = false;
            break;
        default:
            Console.WriteLine("\n\nOopsy, I don't know that command! \n\n");
            break;
    }
    return isValid;
}

If you have a switch statement do not put anything outside the case statements, otherwise you will get that error. 如果您有switch语句,请不要在case语句之外放置任何内容,否则您将收到该错误。

switch (val)
{
    //this line should not be here
    dosomething1(); //==>error
    case "low":
        dosomething2();
        break;
    case "high":
        dosomething3();
        break;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM