DEV Community

Discussion on: Learning Algorithms with JS, Python and Java 5: FizzBuzz

Collapse
 
joefuzz profile image
Joe DuVall

I figured I would take a stab at the Java one, but I couldn't get it to be much more concise. Although, it gave me an opportunity to use IntStream which I recently discovered for myself.

public static void fizzBuzz(final int i) {
        IntStream.range(1, i + 1).forEachOrdered(n -> {
            final boolean divByThree = (n % 3) == 0;
            final boolean divByFive = (n % 5) == 0;
            System.out.print(
                    (divByThree ? "fizz" : "") +
                    (divByFive ? "buzz" : "") +
                    (!divByThree && !divByFive ? n : "") +
                    System.lineSeparator()        
            );
        });
    }

To me, it makes up for the lack of brevity by being more readable, but I recognize that this is more reflective of my style.

Collapse
 
tommy3 profile image
tommy-3

Thank you for your comment. I do like your style!

I'm not sure if it's any better, but we could also rewrite the print statement as:

System.out.println(divByThree || divByFive 
        ? (divByThree ? "fizz" : "") + (divByFive ? "buzz" : "") 
        : n);