I am working on a practice question:
Given a string, return a string made of the first 2 chars (if present), however, include the first char only if it is 'o' and include the second only if it is 'z', so "ozymandias" yields "oz".
startOz("ozymandias") → "oz"
startOz("bzoo") → "z"
startOz("oxx") → "o"
Below is my solution, but I don't know why it shows "incompatible types: char cannot be converted to java.lang.String". I was wondering if anyone can help me with my code. Thank you so much!
public String startOz(String str) {
if (str.length()==1 && str.charAt(0)=='o'){
return 'o';
}
if (str.length()<1){
return "";
}
if (str.length()>=2 && str.charAt(0) =='o' && str.charAt(1) !='z'){
return 'o';
}
if (str.length()>=2 && str.charAt(0) !='o' && str.charAt(1) =='z'){
return 'z';
}
if (str.length()>=2 && str.charAt(0) =='o' && str.charAt(1) =='z'){
return "oz";
} else {
return "";
}
}
'o'is achar."o"would be a string.'o'is achar- a primitive type. It cannot be converted directly to the string"o"(notice the double quotes) - you'd need to explicitly doString.valueOf('o').