Skip to main content

APIzation: Replication Package

[Q#23550985][A#23551020] How to break a while loop from an if condition inside the while loop?

https://stackoverflow.com/q/23550985

I want to break a while loop of the format below which has an if statement. If that if statement is true, the while loop also must break. Any help would be appreciated.

Answer

https://stackoverflow.com/a/23551020

if is not a loop. Simply call break;. Contrived example: If you were actually using nested loops, you would be able to use labels.

APIzation

public static void main(String[] args) {
  int i = 0;
  while (i++ < 10) {
    if (i == 5) break;
  }
  System.out.println(i); //prints 5
}
package com.stackoverflow.api;

public class Human23551020 {

  public static int breakWhileLoop() {
    int i = 0;
    while (i++ < 10) {
      if (i == 5) {
        break;
      }
    }
    //System.out.println(i); //prints 5
    return i;
  }
}

package com.stackoverflow.api;

/**
 * How to break a while loop from an if condition inside the while loop?
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/23551020">https://stackoverflow.com/a/23551020</a>
 */
public class APIzator23551020 {

  public static int breakLoop() {
    int i = 0;
    while (i++ < 10) {
      if (i == 5) break;
    }
    return i;
  }
}