Jason arora Jason arora - 1 year ago 61
Java Question

Output of generating new string array does n't come as expected

You have been two ints, n1 and n2 as input. Return a new String[] containing the numbers from n1 to n2 as strings, except for multiples of 3, use "Fizz" instead of the number, for multiples of 5 use "Buzz", and for multiples of both 3 and 5 use "FizzBuzz

Sample Input #1


Sample Output #1


Sample Input #2


Sample Output #2



I am checking from n1 to n2 wether the nos are divisible by 3 & 5,by 3, and by 5.If it is divisible by 3 I am storing that string in strnew,divisible by 5 store that string in strnew else store that string in strnew,

public String[] generate(int start, int stop)
String strnew[]=new String[stop-start+1];

for(int i=start;i<=stop;i++)


else if(i%3==0)
else if(i%5==0)

return strnew;



What I am doing wrong?Can anyone guide me.


Parameters Actual Output Expected Output

'2' '8' null {'2','Fizz','4','Buzz','Fizz','7','8'}

Answer Source

You need to offset your position in your storage array (start isn't 0). There's no need for a block after strnew and I would prefer braces on the if and else if blocks. Something like,

static String[] generate(int start, int stop) {
    String strnew[] = new String[stop - start + 1];
    for (int i = 0; i < strnew.length; i++) {
        int value = start + i;
        if (value % 15 == 0) {
            strnew[i] = "FizzBuzz";
        } else if (value % 3 == 0) {
            strnew[i] = "Fizz";
        } else if (value % 5 == 0) {
            strnew[i] = "Buzz";
        } else {
            strnew[i] = String.valueOf(value);
    return strnew;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download