I have this generalization of FizzBuzz in Java:
import java.util.Map;
import java.util.TreeMap;
public class GeneralFizzBuzz {
public static void generalFizzBuzz(Map<Integer, String> map,
int start,
int stop) {
String startString = String.valueOf(start);
String stopString = String.valueOf(stop);
// Find the width which can accommodate any line number:
int lineNumberWidth = Math.max(startString.length(),
stopString.length());
// Create the format string for printing line numbers:
String lineNumberFormat = "%" + lineNumberWidth + "d: ";
for (int i = start; i <= stop; ++i) {
// Print the line number and the colon with a space:
System.out.printf(lineNumberFormat, i);
for (Map.Entry<Integer, String> entry : map.entrySet()) {
if (i % entry.getKey() == 0) {
System.out.print(entry.getValue());
}
}
System.out.println();
}
}
public static void main(String[] args) {
Map<Integer, String> map = new TreeMap<>();
map.put(2, "Foo");
map.put(7, "Bar");
map.put(11, "Baz");
generalFizzBuzz(map, -200, 200);
}
}
As always, please tell me whatever comes to mind.
void
and prints to the console? If you're not writing unit tests when coding, then that is the first thing to fix. \$\endgroup\$