Java Reference
In-Depth Information
Continued from previous page
Here's another broken piece of code. This one tries to print a 6
×
4 box of
stars, but it also prints infinitely:
for (int i = 1; i <= 6; i++) {
for (int j = 1; i <= 4; j++) {
System.out.print("*");
}
System.out.println();
}
The problem is on the second line, this time in the inner for loop header's test.
The programmer meant to write j <= 4 but instead accidentally wrote i <= 4 .
Since the value of i is never incremented in the inner loop, the test of i <= 4
never fails, so the inner loop again doesn't terminate.
Pseudocode
As you write more complex algorithms, you will find that you can't just write the
entire algorithm immediately. Instead, you will increasingly make use of the tech-
nique of writing pseudocode.
Pseudocode
English-like descriptions of algorithms. Programming with pseudocode
involves successively refining an informal description until it is easily
translated into Java.
For example, you can describe the problem of drawing a box as
draw a box with 50 lines and 30 columns of asterisks.
While this statement describes the figure, it does not give specific instructions
about how to draw it (that is, what algorithm to use). Do you draw the figure line by
line or column by column? In Java, figures like these must be generated line by line,
because once a println has been performed on a line of output, that line cannot be
changed. There is no command for going back to a previous line in the output.
Therefore, you must output the first line in its entirety, then the second line in its
entirety, and so on. As a result, your decompositions for figures such as these will be
line-oriented at the top level. Thus, a version of the statement that is closer to Java is
for (each of 50 lines) {
draw a line of 30 asterisks.
}
 
Search WWH ::




Custom Search