1

Loop is work fine.

  while (!(list.contains("NORTH SOUTH") || list.contains("SOUTH NORTH") || list.contains("WEST EAST") || list.contains("EAST WEST"))) {


        for (int i = 0; i < list.size(); i++) {
            for (int k = i + 1; k < list.size(); k++) {
                if (list.get(i).contains("NORTH") && list.get(k).contains("SOUTH") ||
                    list.get(i).contains("SOUTH") && list.get(k).contains("NORTH") ||
                    list.get(i).contains("WEST") && list.get(k).contains("EAST") ||
                    list.get(i).contains("EAST") && list.get(k).contains("WEST")) {
                    list.remove(i);
                    list.remove(k - 1);


                  }
            }
        }

My question is:

How to exit while loop with saving list with results?

IMBABOT
  • 121
  • 2
  • 12
  • Does [this](https://stackoverflow.com/questions/886955/breaking-out-of-nested-loops-in-java) helps? – wdc Aug 26 '18 at 11:53
  • As an aside `list.remove(k);` before `list.remove(i);` so you don’t need to subtract 1. It will be clearer to read. – Ole V.V. Aug 26 '18 at 11:57

2 Answers2

3

use the break statement inside the if condition and set a boolean value to a variable.check for the status of that boolean variable just after the for loop ends.if its true then use a break statement to break out of the while loop.

while (!(list.contains("NORTH SOUTH") || list.contains("SOUTH NORTH") || list.contains("WEST EAST") || list.contains("EAST WEST"))) {

    boolean conditionChecker=false;
    for (int i = 0; i < list.size(); i++) {
        for (int k = i + 1; k < list.size(); k++) {
            if (list.get(i).contains("NORTH") && list.get(k).contains("SOUTH") ||
                list.get(i).contains("SOUTH") && list.get(k).contains("NORTH") ||
                list.get(i).contains("WEST") && list.get(k).contains("EAST") ||
                list.get(i).contains("EAST") && list.get(k).contains("WEST")) {
                list.remove(i);
                list.remove(k - 1);
                conditionChecker=true;
                break;

              }
        }
        if(conditionChecker==true){
          break;      
           }
    }
  • conditionChecker shoud set true if condition is observed. In this code code conditionChecker set true after first check, It may have several checks. So I need to break when condition in while loop is observed. – IMBABOT Aug 26 '18 at 12:06
  • the code i have provided will do those. – Nissanka Seneviratne Aug 26 '18 at 12:12
-2

Possible duplicate of: Break while

christian
  • 110
  • 1
  • 2
  • 15