Beginner warm up problem that I can't figure out why isn't working. Thanks for any assistance in advance. (Note: Trying to use substring method not charAt() method.)
----------------------
Given a string, return a string made of the first 2 chars (if present), however include first char only if it is 'o' and include the second only if it is 'z', so "ozymandias" yields "oz".
public String startOz(String str) { String r = ""; if (str.substring(0).equals("o")) r = str.substring(0); if (str.substring(1).equals("z")) r = str.substring(1); return r; }
Expected Run
startOz("ozymandias") → "oz" "" X
startOz("bzoo") → "z" "" X
startOz("oxx") → "o" "" X
startOz("oz") → "oz" "z" X
startOz("ounce") → "o" "" X
startOz("o") → "o" "o" OK
startOz("abc") → "" "" OK
startOz("") → "" "Exception:java.lang.StringIndexOutOfBoundsExcepti on: String index out of range: -1 (line number:8)" X
startOz("zoo") → "" "" OK
startOz("aztec") → "z" "" X
startOz("zzzz") → "z" "" X
startOz("oznic") → "oz" "" X
CodingBat Java Warmup-1 startOz