Home > Enterprise >  How to break from the outer for loop
How to break from the outer for loop

Time:11-07

This program splits a list of strings to line by line. I want to stop/terminate the program after "halted" has been entered. But now it only terminates when "halted" is entered alone and not when it's in a list of strings. Any help is greatly appreciated:)

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter words ");

        while (true) {
            String userText = scanner.nextLine();

            if (userText.equals("halted")) {

                break;
            }

            else {
                String[] pieces = userText.split(" ");

                for (int i = 0; i < pieces.length; i  ) {
                    System.out.println(pieces[i]);

                    if (pieces[i].equals("halted")) {
                        System.out.println(" Stop Program...");
                        break;
                    }

                }

            }

        }
    }

CodePudding user response:

You are breaking the for loop, not while loop, that why the program still running, you can replace the for() with below code

if (Arrays.asList(pieces).contains("halted")){
    System.out.println(" Stop Program...");
    break;
}

CodePudding user response:

Just return; instead, or even System.exit (if you want to exit, then exit, don't attempt to break down the call stack 'nicely'. The computer will do it for you and will do it unfailingly, whereas if you try to break your way out each layer individually, you're writing lots of code, and you can mess it up).

break; without any further argument will find the 'closest' while, do, for, or switch that encloses the break statement, and is taken to mean: Break out of that thing.

You can use labelled breaks instead to break out of any statement or expression that can be braced:

outer:
while (true) {
  ...

if (pieces[i].equals("halted")) break outer;
}

It would be bad code style here though, just return;.

  • Related