Search code examples
javafizzbuzz

Why doesn't this code work? FizzBuzz JAVA


I cant get "FizzBuzz". No matter what the input, the "FizzBuzz" code isn't running. What did I do wrong?

public String[] fizzBuzz(int start, int end) {

int diff = end-start;
String[] array = new String[diff];

for (int i = 0; i < diff; i++) {
    if (start%3 == 0 && start%5 == 0) array[i] = "FizzBuzz";
    if (start%3 == 0 || start%5 == 0) {
        if (start%3 == 0) array[i] = "Fizz";
        if (start%5 == 0) array[i] = "Buzz";
    }
    else {
        array[i] = String.valueOf(start);
    }
    start++;
    }

    return array;
}

Solution

  • Logic in your if statements is a bit busted, using your code as the starting point, you'd have to do something like this.

    if (start%3 == 0 && start%5 == 0) {
        array[i] = "FizzBuzz";
    }
    else if (start%3 == 0 || start%5 == 0) {
        if (start%3 == 0) array[i] = "Fizz";
        if (start%5 == 0) array[i] = "Buzz";
    }
    else {
        array[i] = String.valueOf(start);
    }