The purpose of loop statements is to repeat Java statements many times. There are several kinds of loop statements in Java.
int i = 0; while {i < names.length) ( System.out.println(names[i]); i++; }
for (int i = 0; i < names.length; i++) ( System.out.println(names[i]); }
do ( . . . String ans = JOptionPane.showInputDialog(null, "Do it again (Y/N)?"); } while (ans.equals("Y"));
for (String s : names) ( System.out.println(s); }
There are three general ideas that you will see in many parts of Java.
{}
to enclose multiple statements.If the body of a loop has more than one statement,
you must put the statements inside braces.
If there is only one statement, it is not necessary to
use braces {}
. However, many programmers think it is a
good idea to always use braces to indicate the
scope of statements. Always using braces allows the reader to relax
and not worry about the special single statement case.
All statements inside a loop should be indented 2-4 spaces (the same
as an if
statement.
True/false (boolean) expressions control both loops and the if statement.