== Why is this an issue?

A loop with at most one iteration is equivalent to an `if` statement.
This can confuse developers and make the code less readable since loops are not meant to replace `if` statements.

If the intention was to conditionally execute the block only once, an `if` statement should be used instead.
Otherwise, the loop should be fixed so the loop block can be executed multiple times.

A loop statement with at most one iteration can happen when a statement that unconditionally transfers control,
such as a jump or throw statement, is misplaced inside the loop block.

This rule arises when the following statements are misplaced:

* `break`
* `return`
* `throw`

== How to fix it

=== Code examples

==== Noncompliant code example

[source,java,diff-id=1,diff-type=noncompliant]
----
int i = 0;
while(i < 10) { // Noncompliant; loop only executes once
  System.out.println("i is " + i);
  i++;
  break;
}
----

[source,java,diff-id=2,diff-type=noncompliant]
----
for (int i = 0; i < 10; i++) { // Noncompliant; loop only executes once
  if (i == x) {
    break;
  } else {
    System.out.println("i is " + i);
    return;
  }
}
----

==== Compliant solution

[source,java,diff-id=1,diff-type=compliant]
----
int i = 0;
while (i < 10) {
  System.out.println("i is " + i);
  i++;
}
----

[source,java,diff-id=2,diff-type=compliant]
----
for (int i = 0; i < 10; i++) {
  if (i == x) {
    break;
  } else {
    System.out.println("i is " + i);
  }
}
----

== Resources

=== Documentation

* https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html[Oracle - The for Statement]

ifdef::env-github,rspecator-view[]

'''

== Implementation Specification

(visible only on this page)

include::../message.adoc[]

include::../highlighting.adoc[]

'''

== Comments And Links

(visible only on this page)

include::../comments-and-links.adoc[]

endif::env-github,rspecator-view[]
