Java Reference
In-Depth Information
Because the commas are separators, you want to print one more string than comma
(e.g., two commas to separate the three occurrences of “beetlejuice”). You can use the
classic solution to the fencepost problem to achieve this effect by printing one string
outside the loop and reversing the order of the printing inside the loop:
public static void multiprint(String s, int times) {
System.out.print("[" + s);
for (int i = 2; i <= times; i++) {
System.out.print(", " + s);
}
System.out.println("]");
}
Notice that because you're printing one of the strings before the loop begins, you
have to modify the loop so that it won't print as many strings as it did before.
Adjusting the loop variable i to start at 2 accounts for the first value that is printed
before the loop.
Unfortunately, this solution does not work properly either. Consider what happens
when you ask the method to print a string zero times, as in:
multiprint("please don't", 0);
This call produces the following incorrect output:
[please don't]
You want it to be possible for a user to request zero occurrences of a string, so the
method shouldn't produce that incorrect output. The problem is that the classic solu-
tion to the fencepost problem involves printing one value before the loop begins. To
get the method to behave correctly for the zero case, you can include an if/else
statement:
public static void multiprint(String s, int times) {
if (times == 0) {
System.out.println("[]");
} else {
System.out.print("[" + s);
for (int i = 2; i <= times; i++) {
System.out.print(", " + s);
}
System.out.println("]");
}
}
 
Search WWH ::




Custom Search