Reputation: 550
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)
{"2","Fizz","4","Buzz","Fizz","7","8"}
generate(10,16)
{"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'}
Upvotes: 0
Views: 125
Reputation: 1
public String[] generate(int start, int stop){
String ar[]=new String[stop-start+1];
int num=start;
String s1="Fizz";
String s2="Buzz";
String s3="FizzBuzz";
for(int i=0;i<ar.length;i++){
if((num%3==0)&&(num%5!=0)){
ar[i]=s1;
}
else if((num%5==0)&&(num%3!=0)){
ar[i]=s2;
}
else if((num%3==0)&&(num%5==0)){
ar[i]=s3;
}
else{
String str="";
str=str+num;
ar[i]=str;
}
num=num+1;
}
return ar;
}
Upvotes: 0
Reputation: 201447
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;
}
Upvotes: 2