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?

2
  • Does this helps? Commented Aug 26, 2018 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. Commented Aug 26, 2018 at 11:57

1 Answer 1

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;      
           }
    }
Sign up to request clarification or add additional context in comments.

2 Comments

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.
the code i have provided will do those.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.