Learn Programming in Java
Seaman in Java (Loops)
<<Previous | ToC
| Next >>
We are working through the process of converting your English Seaman into
Java. So far you should have a few lines of variable declarations. Now we look
at the major control structure in the program (besides Sequence). Do you know
what that is in the Five Concepts table below?
What is it that defines the shape of the English program?
Iteration
There must be four, maybe five different iteration loops in the English Seaman.
To translate them to Java you need to figure out what kind of loop each one is.
Is it a specified number of iterations? In the Kitchen computer we specified
the number of iterations as a number (or variable) on the same line with the
"repeat" command. Do you see any of those? In Java those are called "for-loops"
and they were introduced in Lesson #4.
How about loops of unspecified duration, they are
called "while-loops" same page, did you see any of
them? Loops without a termination condition need some other way out, usually
under the control of a Conditional. In Java the command is "break"
instead of "exit". Find those too. You can write them into your Java program,
leaving blank lines for the parts you have not yet translated. Then test your
code by seeing if it will compile.
Conditionals
If you are looking at my English program (instead of your own) you might have
noticed a "repeat 1" command. I use that inside a conditional to make everything
(or nothing) calculate all at once, depending on the condition, because the English language does not have a good way to say "do all this..." Java has a much
better way to spell that kind of Sequence requirement, it's a pair of curly
braces "{..}" surrounding the sequence to be treated together. In any case, Java
requires parentheses "(...)" around the condition test, so if you have a line
like this in English:
if wrong > 7 then exit
it might run perfectly well in the Kitchen computer, but in Java it needs
to be spelled this way:
if (wrong > 7) break;
Can you add the rest of the conditionals to the growing Java program?
Test your code by seeing if it will compile (and fix the problems),
then try to run it. Did it behave properly? You know about the Java debugger,
see if you can discover why it fails (assuming it does: no program this size
ever works correctly the first time you turn it on). This is your program,
you get to do the work.
After your Seaman program works just keeping score, you will be ready to
advance to ASCII (pronounced "ask-key") graphics. Turn
the page.
Five Basic Concepts |
Sequence |
Iteration |
Conditional |
Variables |
Input/Output |
|
<<Previous | ToC
| Next >>
Revised: 2021 May 18