Special Effects and Game Development
in Java(TM) - IF-statements
by Anibal Wainstein
1.4.3 IF-statements
An "if" statement is one of the fundamental commands
in Java. With the if-statement you can test a boolean statement
and then execute different program code depending if it is
true or not (with the ELSE-statement):
if(a > b)
{
String r = "A is greater than B";
}
If you want to execute other code if the statement is not true
then you can add ELSE:
if(a > b)
{
String r = "A is greater than B";
}
else
{
String r = "A is not greater than B";
}
1.4.4 FOR loops
A for loop consists of a bit of code where the "for"
command states how many times the code should be executed.
It is defined in the following way:
for (init; condition; incrementation)
{
code that will be executed
}
The type of loop that will used about 90% of the time in this
course is:
for (int i=0; i<5; i++)
{
code that will be executed
}
What will happen here is that the loop will count to four and
store the subsequent values in the variable "i". The
condition "i<5" states that "i" must
be less than 5, that is, "i" is not allowed to receive
greater values than 4. The expression "i++" will increase
"i" until we reach 4. You can also count down in for-loops:
for (int i=5; i>0; i--)
{ code that will be executed
}
The variable "i" will start with 5 and count down
to 1. The expression "i--" decreases "i"
with 1 each time, but the condition "i>0" makes
sure that "i" never reaches 0.
1.4.5 WHILE loops
The while loop works in a different way. It executes code
as long as an expression is true:
while (condition)
{
code that will be executed
}
The same functionality in the for loop that we had in the last
section can be done with a while loop:
int i = 0;
while (i<4)
{
i++;
}
Note that here we cannot write "i<5" because the
incrementation happens after the comparison. The expression
above will count from 0 to 4 with "i". The decrementation
example in the last section can be done like this:
int i = 5; while (i>0)
{
i--;
}
That is it for now! In the next chapter you will learn how
to program and compile your first applet.
Next Page >>
|