I am testing what knowledge I have with the FizzBuzz tests in Java. This is the one I just completed:
Given a string str, if the string starts with "f" return "Fizz". If the string ends with "b" return "Buzz". If both the "f" and "b" conditions are true, return "FizzBuzz". In all other cases, return the string unchanged.
My code (working):
public String fizzString(String str){
if (str.startsWith("f") && str.endsWith("b")) {
return "FizzBuzz";
}
if (!str.startsWith("f")) {
if (!str.endsWith("b")) {
return str;
} else return "Buzz";
} else return "Fizz";
}
Questions: How can I make this code more efficient? Should I be assigning "Fizz" and "Buzz" to separate string
variables, so that there is just one return
statement at the end of the method? Should there be fewer if
statements - if so, I'm not sure how it would be done. How would you go about the problem?