109k views
5 votes
/* 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.
*/
public String fizzString(String str) {
if( () > 0 &&
str.charAt(0) == 'f' && str.charAt( () - 1) == 'b')
return "FizzBuzz";

if( () > 0 && str.charAt(0) == 'f')
return "Fizz";

if( () > 0 && str.charAt( () - 1) == 'b')
return "Buzz";

return str;
}

1 Answer

3 votes

Final answer:

The function 'fizzString' in Java checks if a string starts with 'f' and/or ends with 'b', returning 'Fizz', 'Buzz', or 'FizzBuzz' accordingly. The missing parts in the if conditions should be completed with 'str.length()' to avoid errors and return the appropriate string based on the set rules.

Step-by-step explanation:

You have presented a question that involves creating a Java function that applies a specific set of rules to a given string. The function fizzString should return "Fizz" if the string starts with an 'f', "Buzz" if it ends with a 'b', and "FizzBuzz" if both conditions are met. If neither condition is met, the original string should be returned unchanged.

The missing parts of your function should check the length of the string to avoid StringIndexOutOfBoundsException. To do this, you need to include str.length() within the if conditions where you have the empty parentheses. Here are the modifications:

public String fizzString(String str) {
if(str.length() > 0 && str.charAt(0) == 'f' && str.charAt(str.length() - 1) == 'b') return "FizzBuzz";
if(str.length() > 0 && str.charAt(0) == 'f') return "Fizz";
if(str.length() > 0 && str.charAt(str.length() - 1) == 'b') return "Buzz";
return str;
}

User Rjminchuk
by
8.2k points