I need some help for FizzBuzz problem. I want to Write a method String fizzBuzz(int start, int end) that returns a String that contains the numbers from start to end listed this way, the consecutive numbers separated by a comma and a single whitespace. For example, the call fizzBuzz(9, 16) would generate the string “fizz, buzz, 11, fizz, 13, 14, fizzbuzz, 16”. For efficiency, this method should internally use a StringBuilder to build up the result string, and convert it to String to be returned in the end.
This is my code:
I feel i should put another condition in if loop, also when i compile this code, it has error "missing return statement". Can you help me?
Method fizzBuzz() has String return type so you must return String after loop.
ashkan ahmadi wrote:when i compile this code, it has error "missing return statement". Can you help me?
Why are you returning String in else clause in loop? did you notice now you have separate if then statements, where in your previous code you had if then else ladder?
When i is 15 then code inside all three if statement gets executed, do you want String to have value "fizzbuzzfizzbuzz" when i is 15?
In addition to above criteria for this method, this method has to work correctly for an empty range where start > end, and a singleton range where start == end.)
You can write if condition and throw IllegalArgumentException when start > end. What do you want to do when start == end?
these are my codes;
i don't know what to write in else conditions to return the number as problem says. in addition, how can i get the right output when start == end?
Here's what your program looks with a formatting style:
There's a compile error that becomes obvious because of a misplaced brace and the if structures have problems. Can you see them now?
Two problems with this logic. You'll need to use if...else if...else if...else. Secondly, if it is divisible by 15 it is therefore divisible by 3 and by 5 so you'll have to move the test for 15 to the first if.
You cannot tell whether the logic in that method is acceptable or not.
would be clearer if written as
This would also fix the aforementioned missing brace issue.
Only one of those could be true yet you have them nested
 Do you really need to handle the case where start > end? Should this be an error? Could you swap start and end? Or would you have to count backwards?
But counting backwards would go in a different method, surely. Part of the problem of that code is what I hinted at yesterday: trying to squeeze too much code into the main method.
Carey Brown wrote:. . . Do you really need to handle the case where start > end? Should this be an error? Could you swap start and end? Or would you have to count backwards?