Java Reference
In-Depth Information
h.equalsIgnoreCase(
"hELLO"
);
// is true
Use a while Loop to Repeat Based on a Condition
You use a
for
loop when you need to run a piece of code a fixed number of
times. But what if you aren't certain just how many times you need to loop?
What if you wanted to loop as long as needed, as long as some other condition
is still true? In that case, you'd use a
while
loop. A
while
loop will keep executing
a piece of code as long as the Boolean condition is true:
while
(stillHungry) {
// ...
// Something better set stillHungry to false!
}
In a way, it's kind of a mix between an
if
statement and a
for
loop: it loops
over code the same way a
for
loop does, but it keeps looping as long as the
condition is true, testing the condition like an
if
does.
And yes, if you forget to change the value to false,
while
will continue forever,
and your entire Minecraft server will be stuck until you kill it or reboot or
lose power, whichever comes first.
Try This Yourself
Now it's time for you to create a loop yourself. Let's go back to
MyHouse.java
, in
~/Desktop/code/BuildAHouse/src/buildahouse
, and instead of creating just one house
with this call:
BuildAHouse.buildMyHouse(width, height);
write a
for
loop that will run ten times, with the
buildMyHouse
call in the body
of the
for
loop. That will make ten houses. Your own mini city!
Edit
MyHouse.java
and add your
for
loop, and then build and install the plugin
as usual:
$
cd Desktop
$
cd BuildAHouse
$
./build.sh
Compiling with javac...
Creating jar file...
Deploying jar to /Users/andy/Desktop/server/plugins...
Completed Successfully.
Stop and restart your server, connect with your client, and type
/buildahouse
again. You now have a set of ten houses!