Pattatharasu Nataraj
Pattatharasu Nataraj

Reputation: 248

trying to break a while loop with a switch case inside switch case

I am receiving some data from an USB component, component will send me continuous data, if I have received the data I have to stop reading the data myself and the component will not stop sending data, I am trying to break the loop if I received some key I tried using boolean, but it is not terminating the loop.

 boolean shouldBreak = false;

    switch(msg.what)
    {               

    case USBAccessoryWhat:
    switch(((USBAccessoryManagerMessage)msg.obj).type) {
    case READ:
        if(accessoryManager.isConnected() == false) {
            return;
        }
        while(true) {
            if(accessoryManager.available() < 2) {
                break;
            }

            switch(commandPacket[0]){
                case 0:
                    test = Integer.toString(commandPacket[0]) + ", " + Integer.toString(commandPacket[1]);
                    Test_one(test);
                break;
                case 1:
                    test = Integer.toString(commandPacket[0]) + ", " + Integer.toString(commandPacket[1]);
                    Test_one(test);
                break;
                case 2:
                    test = Integer.toString(commandPacket[0]) + ", " + Integer.toString(commandPacket[1]);
                    Test_one(test);
                    shouldBreak = true; // have to break here
                break;
                default:
                break;
            } 
             if (shouldBreak) break; //To break this while
        }
        break;

    }
    break;
    }

Upvotes: 1

Views: 3676

Answers (3)

Onur Akan
Onur Akan

Reputation: 51

Try using label with the while loop as below :

label:
    While()
    {
      for()
      {
         break label;
      }
    }

Upvotes: 1

Vincent Mimoun-Prat
Vincent Mimoun-Prat

Reputation: 28583

Just use your flag in the while check:

switch ()
  case  
    bool shouldLoop = true
    while (shouldLoop)
      switch
        case 
          if 
            shouldLoop = false

Upvotes: 1

Erich Schreiner
Erich Schreiner

Reputation: 2058

Try replacing while(true) with while(!shouldBreak) as a break statement only breaks out of the inner-most loop / switch / while etc.

For more details see e.g. Difference between break and continue statement

Upvotes: 2

Related Questions