Censoring Words - Looping Until the Value Passes

Learn more

This is a very short introduction to loops. Some of your fellow classmates contacted me and asked for more. If you want more too, I did a live workshop called Feeling Loopy with Java.

Extra credit

There is a method on string called contains. It checks to see if one string is contained within the other. This seems like a good way to build a master list of words that are not allowed. Why don't see if what they typed is in a long string of bad words.

After you get that working, attempt to take case into account. If your list of bad words that you maintain is all lower cased, you can check the lower case version of the input in the bad string. How do you make a string lowercase?

0:00

At the end of the last video, we talked
about how it was frustrating to do such

0:04

a hard exit when there was a word that
was entered that we wanted to censor.

0:07

It's probably, in fact,

0:08

much better if we continue to prompt
the user until we get a proper value.

0:13

This is a common pattern in programming.

0:15

And it's usually solved using
what is known as a while loop.

0:18

Now what happens is you run the same
code block until a certain condition

0:23

is no longer true.

0:24

In other words, while this
condition is true, do these things.

0:29

Java has a nice feature called a do while,

0:32

which allows us to first run the code
once before any live checking is done.

0:36

Let's use the do while loop to make
sure that the user enters a valid word.

0:41

Okay, so the first thing we wanna do is
locate the book that we wanna repeat.

0:46

So like we said, we wanna continuously
prompt the user until we get a valid now.

0:50

So it looks like here is
a good place to start.

0:56

So in order to repeat the code,
what we'll do is use the keyword do, and

1:00

then we'll do an open bracket there,

1:03

which that signifies that
there's a new code block coming.

1:07

I'm gonna highlight these.

1:08

I'm gonna press the Tab key.

1:11

Great.

1:12

Okay, so now what we want to do is,
we want to change the exiting text,

1:15

because we're no longer gonna exit.

1:17

So let's come over in here, and
we'll change this to say try again,

1:22

and then we'll get rid of the system exit,
because there no where we're gonna exit.

1:29

Okay.

1:30

So next I'm gonna say no,
because we're in the do loop code book,

1:36

and then we're going to put in rail.

1:40

All right and so now, we are gonna loop
while these things are invalid, so

1:44

we already have a statement for
this which is that and I will do, and

1:50

then we'll do this and
we'll end in semi colon.

1:55

All right.

1:56

Now I hope that is starting
to feel wrong to you, and

1:59

that you just I thought that said wait
a second, you said don't repeat yourself.

2:03

Well don't worry,
we'll fix that in the minute.

2:05

So in addition to repeating ourselves, I
just introduced a bug into this code, but