Java Reference
In-Depth Information
The
for
loop is a basic control structure in Java—a way to control the order
of execution of your lines of code. If you need to make a bunch of blocks or
spawn a lot of creepers in a Minecraft world, you'll use a
for
loop. If you need
to loop through all the players that are currently online, you'll probably use
a
for
loop (although there are nicer ways of doing that, which we'll see a little
bit later).
For example, this snippet of code from the guts of a plugin will spawn ten
pigs at your location. Saddle up!
//... somewhere inside a plugin:
for
(
int
i=0; i < 10; i++) {
spawnEntityLiving(location, EntityType.PIG);
}
In this case, the
for
statement will run the instructions in its braces ten times,
so
spawn
will be called ten times, creating ten pigs.
The
for
statement has three parts inside the (), separated by semicolons. Here's
what they do:
int i=0;
The first part declares and
initializes
the looping variable. Here we'll use
i
as our loop counter, and it always starts off at 0—you'll see why later,
but Java always counts starting at 0.
i < 10;
The loop
test
. This tells us when to keep going with the loop (and more
importantly, when to stop). This loop will keep running the code in the
following braces as long as
i
is less than 10. Right now, that would mean
forever, so we need the third part:
i++;
The loop
increment
. This is the part that keeps the loop moving along.
Here we are incrementing the variable
i
by 1 each time through the loop.
Remember,
i++
is shorthand for
i=i+1
. Either way, you are taking the value
of
i
, adding 1 to it, and saving that back as the new value of
i
(you can
use that kind of shortcut anywhere, by the way, not just in loops).
Use an if Statement to Make Decisions
An
if
statement lets you make decisions in code and optionally run a piece of
code depending on whether a condition is true. This is how you make a
computer “think.”