1

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;
}
Aadhish
  • 13
  • 3

3 Answers3

1

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);
}
DominicEU
  • 3,585
  • 2
  • 21
  • 32
0
String s = "" + i;
if ((i % 3) == 0) {
    s += " Fizz";
}
if ((i % 5) == 0) {
    s+= " Buzz";
}
System.out.println(s);

This code snippet placed in a loop will print Fizz, Buzz and Fizz Buzz on i divisible by 3, 5 and 15 respectively.

0

you should try this.

    class FizzBuzz{
    public static void main(String args[]){
        int n = 100;
        for(int i=0;i<=n;i++){

            if((i % 3) == 0 && (i % 5) != 0){
                 System.out.println("Fizz");
            }
            else if((i % 5) == 0 && (i % 3) != 0){
                System.out.println("Buzz");
            }else if((i % 3) == 0 && (i % 5) == 0){
                System.out.println("FizzBuzz");
            }else{
                System.out.println(""+i);
            }

        }
    }
}
sachinsuthariya
  • 435
  • 7
  • 11
  • Nice code, but I can't figure the detail why it doesn't fail. Can you edit the answer and add a description? – Nomce Apr 10 '19 at 07:05
  • Sorry, my friend i didn't get your point. does you ask me to explain the code. OR In which term i should have to add description. – sachinsuthariya Apr 10 '19 at 13:08