Java Reference
In-Depth Information
This solution solves the problem, but it can be confusing because inside the loop
the steps are apparently in reverse order. You can use an if statement and keep the
original order of the steps:
for (the length of the fence) {
plant a post.
if (this isn't the last post) {
attach some wire.
}
}
This variation isn't used as often as the classic solution because it involves both a
loop test and a test inside the loop. Often these tests are nearly identical, so it is ineffi-
cient to test the same thing twice each time the loop executes. But there will be situa-
tions in which you might use this approach. For example, in the classic approach, the
lines of code that correspond to planting a post are repeated. If you were writing a pro-
gram in which this step required a lot of code, you might decide that putting the if
statement inside the loop was a better approach, even if it led to some extra testing.
As an example, consider writing a method called multiprint that will print a
string a particular number of times. Suppose that you want the output on a line by
itself, inside square brackets, and separated by commas. Here are two example calls:
multiprint("please", 4);
multiprint("beetlejuice", 3);
You would expect these calls to produce the following output:
[please, please, please, please]
[beetlejuice, beetlejuice, beetlejuice]
Your first attempt at writing this method might be a simple loop that prints square
brackets outside the loop and prints the string and a comma inside the loop:
public static void multiprint(String s, int times) {
System.out.print("[");
for (int i = 1; i <= times; i++) {
System.out.print(s + ", ");
}
System.out.println("]");
}
Unfortunately, this code produces an extraneous comma after the last value:
[please, please, please, please, ]
[beetlejuice, beetlejuice, beetlejuice, ]
Search WWH ::




Custom Search