Break out of a while loop that contains a switch s

2019-01-08 22:04发布

I am having trouble figuring out how to break out of a loop that contains a switch statement. Break breaks out of the switch, not the loop.

There is probably a more elegant solution to this. I have implemented a flag that starts out as true and gets set to false and ends the loop. Can you offer a better solution?

Background: this code is used in a bar code workflow system. We have PocketPCs that have bar code scanners built in. This code is used in one of those functions. It prompts the user for different pieces of data throughout the routine. This piece allows them to scroll through some inventory records displaying that info on the PocketPC terminal (paged results) and allows them to enter "D" for Done, "Q" to quit.

Here is the current C# example that needs to be improved:

do
{
    switch (MLTWatcherTCPIP.Get().ToUpper())
    {
        case "": //scroll/display next inventory location
            MLTWatcherTCPIP.TerminalPrompt.ScrollBodyTextDown();
            break;
        case "P": //scroll/display previous inventory location
            MLTWatcherTCPIP.TerminalPrompt.ScrollBodyTextDown();
            break;
        case "D": //DONE (exit out of this Do Loop)
            // break; // this breaks out of the switch, not the loop
            // return; // this exists entire method; not what I'm after
            keepOnLooping = false;
            break;
        case "Q": //QUIT (exit out to main menu)
            return;
        default:
            break;
    }
} while (keepOnLooping);

Here is an example of code that does this in VB.NET

Do
    Select Case MLTWatcherTCPIP.Get().ToUpper
        Case "" ''#scroll/display next inventory location
            MLTWatcherTCPIP.TerminalPrompt.ScrollBodyTextDown()
        Case "P" ''#scroll/display previous inventory location
            MLTWatcherTCPIP.TerminalPrompt.ScrollBodyTextUp()
        Case "D" ''#DONE (exit out of this Do Loop)
            Exit Do
        Case "Q" ''#QUIT (exit out to main menu)
            Return
    End Select
Loop

Thanks,

15条回答
唯我独甜
2楼-- · 2019-01-08 22:28

You can't easily break out of the outer loop, but you can continue it.

If you reverse your logic then you get this. Note there is a break immediately after the switch statement to exit the loop.

This isn't very readable code in my opinion, and I think a flag is still best.

   do
         {
            switch (Console.ReadKey().KeyChar.ToString())
            {
                case "U":
                    Console.WriteLine("Scrolling up");
                    continue;

                case "J":
                    Console.WriteLine("Scrolling down");
                    continue;

                case "D": //DONE (exit out of this Do Loop)
                    break;

                case "Q": //QUIT (exit out to main menu)
                    return;

                default:
                    Console.WriteLine("Continuing");
                    continue;
            }

            break;

        } while (true);

        Console.WriteLine("Exited");
查看更多
Ridiculous、
3楼-- · 2019-01-08 22:29

You can replace the switch statement with an if/else statement. No goto needed and the break statement leaves the loop:

do
{
  String c = MLTWatcherTCPIP.Get().ToUpper();

  if (c = "")
    MLTWatcherTCPIP.TerminalPrompt.ScrollBodyTextDown();
  else if (c = "P")
    MLTWatcherTCPIP.TerminalPrompt.ScrollBodyTextUp();
  else if (c = "D")
     break;
  else if (c = "Q")
    return;
  else
  {
    // Handle bad input here.
  }
} while (keepLooping)
查看更多
smile是对你的礼貌
4楼-- · 2019-01-08 22:30

Write something like:

case "Exit/Break" :
                  //Task to do
                    if(true)
                      break;

This break will not be associated with any case. It will belong to the while loop.

查看更多
\"骚年 ilove
5楼-- · 2019-01-08 22:31

A flag is the standard way to do this. The only other way I know of is to use a goto.

查看更多
地球回转人心会变
6楼-- · 2019-01-08 22:33

Why not wrap the switch into a method that returns a boolean to keep on looping? It would have the side benefit of making the code more readable. There's a reason someone wrote a paper saying we don't need goto statements after all ;)

do
{
    bool keepOnLooping = TryToKeepLooping();
} while (keepOnLooping);

private bool TryToKeepLooping()
{
    switch (MLTWatcherTCPIP.Get().ToUpper())
    {
        case "": //scroll/display next inventory location
            MLTWatcherTCPIP.TerminalPrompt.ScrollBodyTextDown();
            break;
        case "P": //scroll/display previous inventory location
            MLTWatcherTCPIP.TerminalPrompt.ScrollBodyTextDown();
            break;
        case "D": //DONE (exit out of this Do Loop)
            // break; // this breaks out of the switch, not the loop
            // return; // this exists entire method; not what I'm after
            return false;
        case "Q": //QUIT (exit out to main menu)
            return true;
        default:
            break;
    }

    return true;
}
查看更多
Rolldiameter
7楼-- · 2019-01-08 22:37

One option here is to refactor this loop into a method ("extract method"), and use return.

查看更多
登录 后发表回答