public class FizzBuzz08 {
public static void main(String[] args) {
int i = 1;
do {
if ((i % 3 == 0) && (i % 5 == 0)) {
System.out.println("FizzBuzz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else {
System.out.println(i);
}
} while (i++ < 100);
}
}
This code isn't dramatically different from the previous entry where the while loop was considered. The body is still on lines 5 through 13, and the first expression is on line 3.
The differences come in the second and third expression. I combined both of them on line 14 for stylistic reasons. First, the order of the expressions would not have been maintained since the increment would occur before the test. I then moved the post increment into the while test expression so we can use the less than operator instead of the less than and equal. One less keystroke. Although since I am programming in Java I don't know why I worry about minimizing keystrokes.
This loop is not a direct decomposition of a for loop. The loop body will always be evaluated once regardless of the truth of the expression. So this is not a good case of the always evaluate logic. So if a do-while smells like a simple while, typical developers can code it correctly. However whether they can use the always evaluate aspect correctly is up for debate.
No comments:
Post a Comment