I will reiterate the need for braces in your statements as well as the importance of avoiding magic numbers in your code. You also asked for how to 'solve' it and this is an alternative approach:
public class FizzBuzz {
public static void main(String[] args) {
final int fizz = 3;
final int buzz = 5;
StringBuilder sb = new StringBuilder("");
for (int i = 1; i <= 100; i++) {
if (i % fizz == 0) {
sb.append("Fizz");
}
if (i % buzz == 0) {
sb.append("Buzz");
}
if (sb.length() == 0) {
System.out.println(i);
} else {
System.out.println(sb.toString());
sb.setLength(0);
}
}
}
}
Why I like it: It's extensible, concise and flexible without giving up on readability. It remains immediately apparent how it works and is intuitive to add several more 'buzz' words and their checks.
I stopped preferring the standard method once It occurred to me how cumbersome additional conditionals would be to write in comparison.
Consider, for example, if you had to print Bazz for multiples of 7. With your code this would mean you would need to check for and print:
- Bazz for multiples of 7.
- BuzzBazz for multiples of 5 and 7.
- FizzBazz for multiples of 3 and 7.
- If you went beyond 100, FizzBuzzBazz for multiples of 3, 5 and 7.
This becomes exponentially more evident the more 'buzz' words you want to add and the higher the upper limit.
Meanwhile, this way, you would only need to add two already familiar lines:
final int Bazz = 7;
to clearly designate that/eliminate ambiguity
and
if (i % bazz == 0) {
sb.append("Bazz");
}
within the loop.
Here are the same ideas implemented using Java 8:
import java.util.stream.IntStream;
public class Java8FizzBuzz {
static final int FIZZ = 3;
static final int BUZZ = 5;
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) {
IntStream.rangeClosed(1, 100).forEach(Java8FizzBuzz::fizzBuzzify);
}
private static void fizzBuzzify(int i) {
if (i % FIZZ == 0) {
sb.append("Fizz");
}
if (i % BUZZ == 0) {
sb.append("Buzz");
}
System.out.println(sb.length() > 0 ? sb.toString() : i);
sb.setLength(0);
}
}
Notice that both implementations have the added benefit of only needing to alter a single character, if for example rather than printing fizz for multiples of 3 one had to print fizz for multiples of 4. This is flexible FizzBuzz, however much that is worth.
if statements
correct, focusing on premature optimization might blur your concentration, and you can get the important things wrong. But even if you get the optimization right, it might not impress the interview, instead she might view you as someone prone to premature optimization. \$\endgroup\$