I made a fizzbuzz program in Java 7 I'd like reviewed.
Given an input file with three numbers in each line, fizz
, buzz
, and count
:
3 5 10
2 7 15
The output, for each line, should be the numbers from 1 to count
, except that multiples of fizz
are replaced with "F"
, multiples of buzz
are replaced by "B"
, and multiples of both with "FB"
:
1 2 F 4 B F 7 8 F B
1 F 3 F 5 F B F 9 F 11 F 13 FB 15
The code, in Java 7:
package com.codeeval.fizzbuzz;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
String path = args[0];
List<String> lines = getFileLines(path);
StringBuilder sb = new StringBuilder();
for (String line : lines){
int[] arguments = getFizzBuzzArguments(line);
int x = arguments[0];
int y = arguments[1];
int n = arguments[2];
String result = fizzBuzz(x, y, n);
sb.append(result).append('\n');
}
System.out.println(sb);
}
public static String fizzBuzz(int x, int y, int n) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= n; i++) {
boolean isX = (i % x == 0);
boolean isY = (i % y == 0);
String append;
if (isX || isY) {
if (isX && isY) { append = "FB"; }
else if (isX) { append = "F"; }
else { append = "B"; }
} else { append = Integer.toString(i); }
sb.append(append);
if (i != n){ sb.append(' '); }
}
return sb.toString();
}
private static List<String> getFileLines(String path) throws IOException {
File file = new File(path);
BufferedReader buffer = new BufferedReader(new FileReader(file));
List<String> lines = new ArrayList<>();
String line;
while ((line = buffer.readLine()) != null) {
line = line.trim();
lines.add(line);
}
return lines;
}
private static int[] getFizzBuzzArguments(String line){
String[] arguments = line.split(" ");
return getArrayOfInts(arguments);
}
private static int[] getArrayOfInts(String[] strings){
int[] ints = new int[strings.length];
for (int i = 0; i < strings.length; i++){
ints[i] = Integer.parseInt(strings[i]);
}
return ints;
}
}