In the next few videos, we're going to
look at loops in Kotlin. Now we've
already seen the for loop, but Kotlin has
other kinds of loops, and in the next few
videos we're going to take a look at
these, as well as revisiting the for loop,
briefly. Now we're going to start off
with the while loop. Now the while
statement executes code continually, as
long as some expression is true. So in
other words, while an expression is true,
the loop will continue looping. Now when
the condition becomes false, the loop
terminates. So looking at our example in
our demo class, our Main.kt, we've
got one of the super vampire objects -
this one down the bottom here, Dracula.
And you can see that I've run the
program to remind us what it's doing, and
we can see that Dracula, being created
with 140 hit points - you can see that
down here in the output - and three lives.
And we're then inflicting twelve points of
damage, but being a King vampire, Dracula
only takes a quarter of that - three
points of damage - and he's also got three
lives. Now the Players in this game will
have to find some pretty impressive
weapons to deal with this monster, but
we're going to take him out using a
while loop. Now as I said, a while loop
can be used to keep repeating a section,
or block of code, until some condition
becomes false. So let's wrap the call to
take damage in a while loop, and
repeatedly inflict damage on Dracula,
until we slay him. Now the condition we want
to test is that Dracula isn't dead. When
Dracula becomes dead,
we can stop looping. So what we want to
do is keep our loop repeating, while
Dracula still has lives left.
When Dracula's lives property reaches
zero, we can stop. So let's have a look at
that code. So we're just going to come
down here, after the println. We're
going to put a while in there; while
dracula.lives is greater than zero.
Then open up a code block, and we'll put
the takeDamage in that code block. So in
other words, so it becomes part of the
loop. If we run this. Now
you can see, looking at the output, it
took quite some time - in other words,
quite a lot of attacks - before we get
Dracula's lives down to zero. So a while
statement starts off with the word while,
as you can see on line 15, and then in
brackets, there's a boolean expression.
And what I mean by that is, it has to
evaluate to true or false. So while the
condition is true, the code in the
brackets, the parentheses, will
continually be executed until either the
boolean expression becomes false - and you
set that in the code, perhaps - or a break
is found in the code. And I'm going to
show you an example of a break as well.
So while is very useful for doing
things like cycling or waiting for a
particular event to happen - for example,
while there's still data in a file,
continue reading from that file. It's
very useful to continually be checking
something until a particular condition
changes. Now in our example, Dracula's
lives are checked each time around the
loop. If Dracula still has lives left, the
code inside the loop gets executed. Once
all the code's executed - we only have
one line of code in here, which you can see on
line 16, in our loop, but there could
be many more. Once all that code's
executed, the code's checked again to see
if it's still true. Now
Dracula may have been a very powerful
enemy, with three lives and 140 hit
points, but the outcome wasn't in
question. Our wallet will keep going
around until Dracula's lives drop to
zero. So the condition in our loop is
this here, in parentheses; dracula dot
lives greater than zero.
While that evaluates to true, we keep
looping and inflict more damage. And you
can see as I scroll up in the output, the
first life lasted quite a while -
basically, as the hit points dropped from
140 by three each time. Now when the hit
points Dracula has left would have
dropped below zero, he loses a life
instead. So the last two lives were lost,
consequently, very quickly. The important
thing, though, is that the code kept
executing, as long as Dracula still had
at least one life left.
Once the lives became zero, the condition
is no longer true, and the while loop
terminates. So that's a while loop. As
long as the condition evaluates to true,
all this code between these curly braces -
in this case, it's just a single line, but
it could again, be multiple lines - all
that code between those curly braces
keeps executing. When something happens
to make the condition evaluate to false,
the while loop stops looping and
terminates. Now the code between the curly
braces is called a block. So whenever I
talk about a code block or a block of
code, I mean code inside curly braces. So
looking at this entire main method, you
can see that if I select all that
code there between these starting and
closing curly braces, is also a block
of code. So you can see that a block of
code, or a code block can contain other
code blocks.
Okay, so there's another way to get out
of a while loop, and that's to break out
of it. In fact, you can break out of any
loop, but we'll look at this first with
our while loop. So to demonstrate break,
we're going to give Dracula another
method - or more accurately, we're going to
give the VampyreKing class another
method. Now, you don't get to live as long
as Dracula without having a good sense
of self-preservation, so we're going to
give our VampyreKings a runAway method.
So let's start off - we go to our Vampyre
King. We're going to write this function
in a naive way, and then we're going to
change it to more Kotlin-like code. So
come down here below the takeDamage for
Vampyreking, and we're going to create
this function; fun runAway
parenthesis colon Boolean, left and right
curly braces. We're going to put if
parentheses lives is less than 2, return
true - and have an else outside of the
code block and create another code block
with it after the else - return false. So
it's a very simple method, that returns
true if the number of lives drops below
2, and false otherwise. Now as I
mentioned, I've written that code in
quite a long way. In fact, Android Studio,
if we come over here, is actually
complaining a little bit, to Remove the
redundant if statement. So what we can do
is use that light bulb to convert this
into a more idiomatic form.
So we could do, click on that, and that
does exactly the same thing but in a
less verbose way. So if lives is less than 2,
it'll return true, otherwise it returns
false, which does exactly the same thing.
So the condition, lives less than 2,
evaluates to true or false. So we can
just return the result of evaluating the
expression, instead of having to
explicitly test it. Now if you prefer to
write code like this longhand, until you
get the hang of it - that's that first
example, before we just converted it to
this more idiomatic format - that's fine,
but be aware that a lot of code you read
will do it this shorter way, as I've
shown on line 15.
Okay, so Dracula now runs away if he
loses too many lives. So let's test that
in our while loop. So we're gonna go back to Main. So
we've still got our while dracula's lives is
greater than zero, and what we're going
to do here before the takeDamage, we're
going to put if, then parenthesis,
dracula.runAway. And then add
a code block, so println Dracula
ran away.
We'll put else, then we'll wrap the take
Damage in another code block as well,
like so. So let's just try running this
and confirm that it works.
Now notice that what's happening
here; Dracula runs away when his
lives drops below 2, but once he's run
away the condition can never become true,
because we can't inflict any more damage.
So I'm gonna stop the program, at this point,
by clicking on this red square in the
top left-hand corner. So you can see that
the loop has got out of control and it's just
looping around and around forever. So
I'll scroll up a bit - quite
a bit actually, because we let it run for
quite a while - right up towards the top.
In fact, it's actually cleared out the
run buffer so we can't see anything
above that. Basically, it's gone around
hundreds of times, while I was talking
here. So this is called an infinite loop,
and our program was stuck in it. Now
because there was no way for the
condition to become false, it just kept
on looping. So what we want to do is
somehow break out of the loop, when
Dracula runs away. So we can do that with
a break statement. So after the code that
says, or that actually prints out the fact
that Dracula ran away, we're going to add
a break there. So then a break on that
next line. And now if we run this again,
we should finally no longer get an
infinite loop. And you can see what
happened was; lost a life, lost a life and
at that point, lives was less than 2. So
Dracula ran away and the program now
exits because we've added this break
statement on line 18. So basically, Kotlin
jumped out of the loop at that point, and
prevented us from getting stuck going
round and round forever. So you can see
that break's very useful, when you need to
terminate a loop without waiting for the
condition to become false. Now that can
happen for all sorts of reasons. I
mentioned using a while loop to keep
reading from a file, as long as there's data
available, as an example. Now if we were
searching for something in the
file, you wouldn't want to keep reading
the data after finding it. So in that
case, you could use break to terminate
the loop, instead of having to read
through to the end of the file. Now we'll
be seeing break used often in the
course, so you'll see plenty of examples
of it in real use. Now there's something else
you can do in a loop, and that's to
continue. So basically, any time you
execute a continue statement, the code
goes back to the top of the loop, without
executing any more of the code in the
loop. So continue isn't used as often as
break, but it can be useful in some
situations. To see how we could use
continue, let's give Dracula the ability
to dodge some blows.
Now games such as this are normally
played using dice, so we need to
introduce a bit of chance into the game.
So I'm going to use another Java class
called Random, which we'll use to give
Dracula a chance to dodge a blow. So what
we're going to do is add a dodges
function to the VampyreKing class, and
that's going to return true if the King
vampire dodges successfully, and false
otherwise. So going back to VampyreKing,
below the runAway function, add a
definition for dodges, function dodges,
parentheses colon Boolean, left and right
curly braces. Then we're going to type
val rand equals, Random with a capital R
in parentheses. Then val chance equals
rand.nextInt and 3 in parentheses.
Then we're going to put, actually, what we'll
do there is we'll make that a six, not a
three - we'll talk about this shortly. Now on
the next line, if parentheses chance is
greater than three, and we're going to print an
output, the fact that Dracula dodges;
println Dracula dodges, return true.
Otherwise, outside of the if code block,
we're going to do a return false.
Okay, so there's our dodges
function. And what should have happened
when you typed Random, Android Studio
should have automatically imported the
java.util package, and that's where
the Random class is defined. If for some
reason it hasn't, and you can see in my case
it has - import java.util.* -
but if we're getting an error there, just type
that in as line one, and that will get that
error to disappear. Alright, so
this Random class has a nextInt method
that is being used here on line 22, and
that returns a number between 0 and 5. So
it's like a six-sided dice, but labelled
starting at zero rather than 1. Now we
can specify the range by passing an int
argument to nextInt. So if we wanted to
emulate a 20-sided dice, for example, we'd
pass 20 as the argument. Remember that
computers count the 0 as a number, so
we'd actually get a value from 0 to 19,
in that scenario, returned instead. And
here we're using 6 as the argument, and
we're gonna get a value returned between
zero to five. And consequently, with the if
code, we're doing if chance is greater
than 3, so the VampyreKing has got a one
in three chance of dodging a blow. So going
back to our Main class, we can now modify
the while loop to check if Dracula
dodges. And just below the while dracula
dot lives greater than 0, so the
first line before the dracula.run
Away, we're gonna put if and parentheses,
dracula.dodges. Then add a code block -
we're going to type continue and leave
it like that, and leave the other
code as is. So now if Dracula dodges, the
continue statement should get executed,
and that should cause the rest of the
loop's block to be skipped, and the code
goes back to the while statement and
tests the condition again. I'm going to
run the program, and keep in mind that this is
now a bit random, so we'll get different
results each time we run the program. We
should be able to see Dracula dodging
some of the blows. You can see some
dodges there, as well as taking damage.
And you can see that you've got two dodges
there but if I run this again, the results
will be entirely random.
And you can see we've got different output
each time. So that's a quick overview of
the while loop. They're great when you
want to keep repeating a block of code,
as long as the condition remains true.
Once the condition becomes false, the
loop terminates. Now we can also break
out of the loop, as we saw, as well as
skipping back to the beginning without
executing the rest of the code in the
loop, by using a using a continue
statement. I've also shown you the
Random class. Now you could modify the
program, so that instead of giving,
always giving Dracula 20 points of
damage, you get a new random number each
time you call the random.nextInt
method. So you could emulate a 20-sided
dice and make the program work a bit more
like Dungeons & Dragons. Alright, so in
the next video, we're gonna have a look
at the for loop. See you in the next video.