gudii9
asked on
java substring issue
Hi,
I am trying below challenge
http://codingbat.com/prob/p183592
I wrote as below
public String front22(String str) {
if(str.length()>=2){
return str.substring(0,2)+str+str.substring(0,2);
}
if(str.length()==2){
return str+str+str;
}
if(str.length()==1){
return str+str+str;
}
return null;
}
My test case failing for below scenario
front22("") → "" "null" X
Please advise
Please clarify what isn't working about the code you posted.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
public String front22(String str) {
if(str.length()>=2){
return str.substring(0,2)+str+str.substring(0,2);
}
if(str.length()==2){
return str+str+str;
}
if(str.length()==1){
return str+str+str;
}
return "";
}
I see above one is working for all scenarios.
Having multiple retuns in each if and also outside if loops at the end of the method looks bit odd to me. Is that is general practice please advise
You can't say that it is necessarily the "general practice" but it is certainly one possible valid practice, it just depends on the situation. The one definite thing here is that since your function specifies that it will return a String, you need to make sure that every possible code execution path returns a value that can be type String. In this case, if any of the "if" statements match then it will return the String that is specified within them. If none of the "if" match then code execution will continue further and reach the return ""; which ensures that a String value is returned. Nothing terribly odd about it.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Math.min(2,str.length()
what is the purpose of above line. Please advise
Math.min(a,b) returns the smaller of the two values "a" and "b".
So
Math.min(2, str.length()) returns either the length of the string or the value 2, whichever is smaller.
So for a string longer than 2 it returns 2.
For a string length 1, it returns 1.
For a string length 0, it returns 0.
Can you see now how that makes the whole thing work?
So
Math.min(2, str.length()) returns either the length of the string or the value 2, whichever is smaller.
So for a string longer than 2 it returns 2.
For a string length 1, it returns 1.
For a string length 0, it returns 0.
Can you see now how that makes the whole thing work?
ASKER
but not working. I wonder why? please advise