Jason arora - 2 months ago 4
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

generate(2,8)

# Sample Output #1

{"2","Fizz","4","Buzz","Fizz","7","8"}

generate(10,16)

# Sample Output #2

{"Buzz","11","Fizz","13","14","FizzBuzz",16}

MyApproach

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++)

{

if((i%3==0)&&(i%5==0))
strnew[i]="FizzBuzz";
else if(i%3==0)
strnew[i]="Fizz";
else if(i%5==0)
strnew[i]="Buzz";
else
strnew[i]=""+i;
}

return strnew;
}

}
``````

MyQuestion:

What I am doing wrong?Can anyone guide me.

Output

``````Parameters  Actual Output   Expected Output

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

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;
}
``````