Reputation: 57
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 "";
}
}
Upvotes: 0
Views: 158
Reputation: 121819
Rainmaker et al are correct: the problem is that your method should return a String (a Java object), not a char (a Java primitive). One good solution to the compile error is to return "o" (double quotes).
But perhaps you might find this a simpler solution:
public static boolean isNullOrEmpty(String s) {
return s == null || s.isEmpty();
}
public String startOz(String str) {
if (isNullOrEmpty(str)) {
return "";
} else if (str.startsWith("oz")) {
return "oz";
} else if (str.charAt(0) == 'o') {
return "o";
} else if (str.length() > 1 && str.charAt(1) == 'z') {
return "z";
} else {
return "";
}
Upvotes: 1
Reputation: 18255
You cannot retreive a char
instead of Stirng
. Do use String.valueOf(ch)
instead.
By the way, just be a simple man! You can do the same with much less code.
public static String startOz(String str) {
String res = "";
if (str != null) {
if (str.length() > 0 && str.charAt(0) == 'o')
res += 'o';
if (str.length() > 1 && str.charAt(1) == 'z')
res += 'z';
}
return res;
}
Answer to comment.
StringBuilder
is a correct way to build a String
, because String
is immutable in Java
. In case you are a beginner, I removed it.<condition> ? <true> : <false>
is called a ternary operand. if is similar like if(<condition>) <true> else <false>;
trim()
to remove \0
from the beginning and the end of the string. A also removed it.You can see my updated result.
Upvotes: 0
Reputation: 118
When you type a string in single quotation marks, it tells the compiler to consider whatever follows as a single character. Double quotation marks indicate a string. The function cannot return a char when it is expecting a String.
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 "";
}
}
Upvotes: 4