Java Reference
In-Depth Information
It's just like the real world. We run on “if” statements all the time. If your age
is >= 16, you are allowed to drive. If the door is unlocked, you can open it, or
else you cannot. If the command given to Minecraft is equal to "hello" , then
send a message. If your health drops to zero, you're dead.
This is what it looks like in Java:
if (something) {
// run this code...
The part in parentheses ( something ) can be anything that turns out true or false ;
in other words, a Boolean condition (more on that in just a second).
If you need to, you can also put code in to run if something is true and
specify what to run if it's false:
if (something) {
// run this code if something is true
} else {
// run this code if something is false
For example, here's a fragment of code that will say something different
depending on whether the String in the variable myName contains Notch.
if (myname.equalsIgnoreCase( "Notch" )) {
say( "Greetings from Notch!" );
} else {
say( "Notch isn't here anymore." );
if statements (with or without the else ) are critical to programming: that's how
you can get the computer to make decisions and pretend to “think.” Pretty
powerful stuff, but really simple to use.
Compare Stuff with Boolean Conditions
if statements decide what to run based on whether
something is true . But just what is true ?
Besides numbers and strings that we've seen, you can
also make a variable that keeps track of whether some-
thing is turned on, like a toggle switch. In Minecraft, we'll
use this to determine all sorts of things: if a player is on
the ground or not, if a string matches another string,
whether to use a game event or ignore it, and much more.
Search WWH ::

Custom Search