Skip to content

Instantly share code, notes, and snippets.

@kazuhito-m
Last active January 25, 2024 11:18
Show Gist options
  • Save kazuhito-m/b604248cff609b622dad7e487e6d4689 to your computer and use it in GitHub Desktop.
Save kazuhito-m/b604248cff609b622dad7e487e6d4689 to your computer and use it in GitHub Desktop.
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class FizzBuzzSourceGenerator {
public static void main(String[] args) throws FileNotFoundException {
String sourceText = "public class FizzBuzz {\n\tpublic static void main(String[] args) {"
+ generateOutputPart()
+ "\n\t}\n}";
outputFile("FizzBuzz.java", sourceText);
}
private static String generateOutputPart() {
return IntStream.rangeClosed(1, 100)
.mapToObj(FizzBuzzSourceGenerator::generateFizzBuzzTextOf)
.map(s -> String.format("\n\t\tSystem.out.print(\"%s \");", s))
.collect(Collectors.joining());
}
private static String generateFizzBuzzTextOf(int number) {
String result = "";
if (number % 3 == 0) result += "Fizz";
if (number % 5 == 0) result += "Buzz";
return result.length() == 0 ? String.valueOf(number) : result;
}
private static void outputFile(String filePath, String text) throws FileNotFoundException {
try (PrintWriter writer = new PrintWriter(filePath)) {
writer.println(text);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment